当前位置: 首页>>代码示例>>Golang>>正文


Golang crypto.Sha3Hash函数代码示例

本文整理汇总了Golang中github.com/expanse-project/go-expanse/crypto.Sha3Hash函数的典型用法代码示例。如果您正苦于以下问题:Golang Sha3Hash函数的具体用法?Golang Sha3Hash怎么用?Golang Sha3Hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Sha3Hash函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: mine

// mine generates a testnet struct literal with nodes at
// various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) {
	n.target = target
	n.targetSha = crypto.Sha3Hash(n.target[:])
	found := 0
	for found < bucketSize*10 {
		k := newkey()
		id := PubkeyID(&k.PublicKey)
		sha := crypto.Sha3Hash(id[:])
		ld := logdist(n.targetSha, sha)
		if len(n.dists[ld]) < bucketSize {
			n.dists[ld] = append(n.dists[ld], id)
			fmt.Println("found ID with ld", ld)
			found++
		}
	}
	fmt.Println("&preminedTestnet{")
	fmt.Printf("	target: %#v,\n", n.target)
	fmt.Printf("	targetSha: %#v,\n", n.targetSha)
	fmt.Printf("	dists: [%d][]NodeID{\n", len(n.dists))
	for ld, ns := range n.dists {
		if len(ns) == 0 {
			continue
		}
		fmt.Printf("		%d: []NodeID{\n", ld)
		for _, n := range ns {
			fmt.Printf("			MustHexID(\"%x\"),\n", n[:])
		}
		fmt.Println("		},")
	}
	fmt.Println("	},")
	fmt.Println("}")
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:34,代码来源:table_test.go

示例2: TestGetAuthContent

func TestGetAuthContent(t *testing.T) {
	dir, err := ioutil.TempDir("", "httpclient-test")
	if err != nil {
		t.Fatal("cannot create temporary directory:", err)
	}
	defer os.RemoveAll(dir)
	client := New(dir)

	text := "test"
	hash := crypto.Sha3Hash([]byte(text))
	if err := ioutil.WriteFile(path.Join(dir, "test.content"), []byte(text), os.ModePerm); err != nil {
		t.Fatal("could not write test file", err)
	}
	content, err := client.GetAuthContent("file:///test.content", hash)
	if err != nil {
		t.Errorf("no error expected, got %v", err)
	}
	if string(content) != text {
		t.Errorf("incorrect content. expected %v, got %v", text, string(content))
	}

	hash = common.Hash{}
	content, err = client.GetAuthContent("file:///test.content", hash)
	expected := "content hash mismatch 0000000000000000000000000000000000000000000000000000000000000000 != 9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658 (exp)"
	if err == nil {
		t.Errorf("expected error, got nothing")
	} else {
		if err.Error() != expected {
			t.Errorf("expected error '%s' got '%v'", expected, err)
		}
	}

}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:33,代码来源:httpclient_test.go

示例3: Hash

// Hash returns the SHA3 hash of the envelope, calculating it if not yet done.
func (self *Envelope) Hash() common.Hash {
	if (self.hash == common.Hash{}) {
		enc, _ := rlp.EncodeToBytes(self)
		self.hash = crypto.Sha3Hash(enc)
	}
	return self.hash
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:8,代码来源:envelope.go

示例4: handle

func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error {
	if expired(req.Expiration) {
		return errExpired
	}
	if t.db.node(fromID) == nil {
		// No bond exists, we don't process the packet. This prevents
		// an attack vector where the discovery protocol could be used
		// to amplify traffic in a DDOS attack. A malicious actor
		// would send a findnode request with the IP address and UDP
		// port of the target as the source address. The recipient of
		// the findnode packet would then send a neighbors packet
		// (which is a much bigger packet than findnode) to the victim.
		return errUnknownNode
	}
	target := crypto.Sha3Hash(req.Target[:])
	t.mutex.Lock()
	closest := t.closest(target, bucketSize).entries
	t.mutex.Unlock()

	p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
	// Send neighbors in chunks with at most maxNeighbors per packet
	// to stay below the 1280 byte limit.
	for i, n := range closest {
		p.Nodes = append(p.Nodes, nodeToRPC(n))
		if len(p.Nodes) == maxNeighbors || i == len(closest)-1 {
			t.send(from, neighborsPacket, p)
			p.Nodes = p.Nodes[:0]
		}
	}
	return nil
}
开发者ID:5mil,项目名称:go-expanse,代码行数:31,代码来源:udp.go

示例5: NewProgram

// NewProgram returns a new JIT program
func NewProgram(code []byte) *Program {
	program := &Program{
		Id:           crypto.Sha3Hash(code),
		mapping:      make(map[uint64]uint64),
		destinations: make(map[uint64]struct{}),
		code:         code,
	}

	programs.Add(program.Id, program)
	return program
}
开发者ID:5mil,项目名称:go-expanse,代码行数:12,代码来源:jit.go

示例6: newNode

func newNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node {
	if ipv4 := ip.To4(); ipv4 != nil {
		ip = ipv4
	}
	return &Node{
		IP:  ip,
		UDP: udpPort,
		TCP: tcpPort,
		ID:  id,
		sha: crypto.Sha3Hash(id[:]),
	}
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:12,代码来源:node.go

示例7: Bootstrap

// Bootstrap sets the bootstrap nodes. These nodes are used to connect
// to the network if the table is empty. Bootstrap will also attempt to
// fill the table by performing random lookup operations on the
// network.
func (tab *Table) Bootstrap(nodes []*Node) {
	tab.mutex.Lock()
	// TODO: maybe filter nodes with bad fields (nil, etc.) to avoid strange crashes
	tab.nursery = make([]*Node, 0, len(nodes))
	for _, n := range nodes {
		cpy := *n
		cpy.sha = crypto.Sha3Hash(n.ID[:])
		tab.nursery = append(tab.nursery, &cpy)
	}
	tab.mutex.Unlock()
	tab.refresh()
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:16,代码来源:table.go

示例8: node

// node retrieves a node with a given id from the database.
func (db *nodeDB) node(id NodeID) *Node {
	blob, err := db.lvl.Get(makeKey(id, nodeDBDiscoverRoot), nil)
	if err != nil {
		glog.V(logger.Detail).Infof("failed to retrieve node %v: %v", id, err)
		return nil
	}
	node := new(Node)
	if err := rlp.DecodeBytes(blob, node); err != nil {
		glog.V(logger.Warn).Infof("failed to decode node RLP: %v", err)
		return nil
	}
	node.sha = crypto.Sha3Hash(node.ID[:])
	return node
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:15,代码来源:database.go

示例9: GetAuthContent

func (self *HTTPClient) GetAuthContent(uri string, hash common.Hash) ([]byte, error) {
	// retrieve content
	content, err := self.Get(uri, "")
	if err != nil {
		return nil, err
	}

	// check hash to authenticate content
	chash := crypto.Sha3Hash(content)
	if chash != hash {
		return nil, fmt.Errorf("content hash mismatch %x != %x (exp)", hash[:], chash[:])
	}

	return content, nil

}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:16,代码来源:httpclient.go

示例10: DecodeRLP

// DecodeRLP decodes an Envelope from an RLP data stream.
func (self *Envelope) DecodeRLP(s *rlp.Stream) error {
	raw, err := s.Raw()
	if err != nil {
		return err
	}
	// The decoding of Envelope uses the struct fields but also needs
	// to compute the hash of the whole RLP-encoded envelope. This
	// type has the same structure as Envelope but is not an
	// rlp.Decoder so we can reuse the Envelope struct definition.
	type rlpenv Envelope
	if err := rlp.DecodeBytes(raw, (*rlpenv)(self)); err != nil {
		return err
	}
	self.hash = crypto.Sha3Hash(raw)
	return nil
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:17,代码来源:envelope.go

示例11: GetAuthContent

func (self *DocServer) GetAuthContent(uri string, hash common.Hash) (content []byte, err error) {
	// retrieve content
	content, err = self.Get(uri, "")
	if err != nil {
		return
	}

	// check hash to authenticate content
	chash := crypto.Sha3Hash(content)
	if chash != hash {
		content = nil
		err = fmt.Errorf("content hash mismatch %x != %x (exp)", hash[:], chash[:])
	}

	return

}
开发者ID:este-xx,项目名称:go-expanse,代码行数:17,代码来源:docserver.go

示例12: TestUDP_findnode

func TestUDP_findnode(t *testing.T) {
	test := newUDPTest(t)
	defer test.table.Close()

	// put a few nodes into the table. their exact
	// distribution shouldn't matter much, altough we need to
	// take care not to overflow any bucket.
	targetHash := crypto.Sha3Hash(testTarget[:])
	nodes := &nodesByDistance{target: targetHash}
	for i := 0; i < bucketSize; i++ {
		nodes.push(nodeAtDistance(test.table.self.sha, i+2), bucketSize)
	}
	test.table.stuff(nodes.entries)

	// ensure there's a bond with the test node,
	// findnode won't be accepted otherwise.
	test.table.db.updateNode(newNode(
		PubkeyID(&test.remotekey.PublicKey),
		test.remoteaddr.IP,
		uint16(test.remoteaddr.Port),
		99,
	))
	// check that closest neighbors are returned.
	test.packetIn(nil, findnodePacket, &findnode{Target: testTarget, Expiration: futureExp})
	expected := test.table.closest(targetHash, bucketSize)

	waitNeighbors := func(want []*Node) {
		test.waitPacketOut(func(p *neighbors) {
			if len(p.Nodes) != len(want) {
				t.Errorf("wrong number of results: got %d, want %d", len(p.Nodes), bucketSize)
			}
			for i := range p.Nodes {
				if p.Nodes[i].ID != want[i].ID {
					t.Errorf("result mismatch at %d:\n  got:  %v\n  want: %v", i, p.Nodes[i], expected.entries[i])
				}
			}
		})
	}
	waitNeighbors(expected.entries[:maxNeighbors])
	waitNeighbors(expected.entries[maxNeighbors:])
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:41,代码来源:udp_test.go

示例13: Run

// Run loops and evaluates the contract's code with the given input data
func (self *Vm) Run(context *Context, input []byte) (ret []byte, err error) {
	self.env.SetDepth(self.env.Depth() + 1)
	defer self.env.SetDepth(self.env.Depth() - 1)

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			// In case of a VM exception (known exceptions) all gas consumed (panics NOT included).
			context.UseGas(context.Gas)

			ret = context.Return(nil)
		}
	}()

	if context.CodeAddr != nil {
		if p := Precompiled[context.CodeAddr.Str()]; p != nil {
			return self.RunPrecompiled(p, input, context)
		}
	}

	var (
		codehash = crypto.Sha3Hash(context.Code) // codehash is used when doing jump dest caching
		program  *Program
	)
	if EnableJit {
		// Fetch program status.
		// * If ready run using JIT
		// * If unknown, compile in a seperate goroutine
		// * If forced wait for compilation and run once done
		if status := GetProgramStatus(codehash); status == progReady {
			return RunProgram(GetProgram(codehash), self.env, context, input)
		} else if status == progUnknown {
			if ForceJit {
				// Create and compile program
				program = NewProgram(context.Code)
				perr := CompileProgram(program)
				if perr == nil {
					return RunProgram(program, self.env, context, input)
				}
				glog.V(logger.Info).Infoln("error compiling program", err)
			} else {
				// create and compile the program. Compilation
				// is done in a seperate goroutine
				program = NewProgram(context.Code)
				go func() {
					err := CompileProgram(program)
					if err != nil {
						glog.V(logger.Info).Infoln("error compiling program", err)
						return
					}
				}()
			}
		}
	}

	var (
		caller = context.caller
		code   = context.Code
		value  = context.value
		price  = context.Price

		op      OpCode             // current opcode
		mem     = NewMemory()      // bound memory
		stack   = newstack()       // local stack
		statedb = self.env.State() // current state
		// For optimisation reason we're using uint64 as the program counter.
		// It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Pratically much less so feasible.
		pc = uint64(0) // program counter

		// jump evaluates and checks whether the given jump destination is a valid one
		// if valid move the `pc` otherwise return an error.
		jump = func(from uint64, to *big.Int) error {
			if !context.jumpdests.has(codehash, code, to) {
				nop := context.GetOp(to.Uint64())
				return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
			}

			pc = to.Uint64()

			return nil
		}

		newMemSize *big.Int
		cost       *big.Int
	)

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			self.log(pc, op, context.Gas, cost, mem, stack, context, err)
		}
	}()

	// Don't bother with the execution if there's no code.
	if len(code) == 0 {
		return context.Return(nil), nil
	}

	for {
//.........这里部分代码省略.........
开发者ID:este-xx,项目名称:go-expanse,代码行数:101,代码来源:vm.go

示例14: TestEthashVerifyValid

		nonce:       0x318df1c8adef7e5e,
		mixDigest:   common.HexToHash("144b180aad09ae3c81fb07be92c8e6351b5646dda80e6844ae1b697e55ddde84"),
	},
	// from proof of concept nine testnet, epoch 2
	{
		number:      60000,
		hashNoNonce: common.HexToHash("5fc898f16035bf5ac9c6d9077ae1e3d5fc1ecc3c9fd5bee8bb00e810fdacbaa0"),
		difficulty:  big.NewInt(2467358),
		nonce:       0x50377003e5d830ca,
		mixDigest:   common.HexToHash("ab546a5b73c452ae86dadd36f0ed83a6745226717d3798832d1b20b489e82063"),
	},
}

var invalidZeroDiffBlock = testBlock{
	number:      61440000,
	hashNoNonce: crypto.Sha3Hash([]byte("foo")),
	difficulty:  big.NewInt(0),
	nonce:       0xcafebabec00000fe,
	mixDigest:   crypto.Sha3Hash([]byte("bar")),
}

func TestEthashVerifyValid(t *testing.T) {
	exp := New()
	for i, block := range validBlocks {
		if !exp.Verify(block) {
			t.Errorf("block %d (%x) did not validate.", i, block.hashNoNonce[:6])
		}
	}
}

func TestEthashVerifyInvalid(t *testing.T) {
开发者ID:este-xx,项目名称:go-expanse,代码行数:31,代码来源:ethash_test.go

示例15: Run

// Run loops and evaluates the contract's code with the given input data
func (self *Vm) Run(contract *Contract, input []byte) (ret []byte, err error) {
	self.env.SetDepth(self.env.Depth() + 1)
	defer self.env.SetDepth(self.env.Depth() - 1)

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			// In case of a VM exception (known exceptions) all gas consumed (panics NOT included).
			contract.UseGas(contract.Gas)

			ret = contract.Return(nil)
		}
	}()

	if contract.CodeAddr != nil {
		if p := Precompiled[contract.CodeAddr.Str()]; p != nil {
			return self.RunPrecompiled(p, input, contract)
		}
	}

	// Don't bother with the execution if there's no code.
	if len(contract.Code) == 0 {
		return contract.Return(nil), nil
	}

	var (
		codehash = crypto.Sha3Hash(contract.Code) // codehash is used when doing jump dest caching
		program  *Program
	)
	if EnableJit {
		// If the JIT is enabled check the status of the JIT program,
		// if it doesn't exist compile a new program in a seperate
		// goroutine or wait for compilation to finish if the JIT is
		// forced.
		switch GetProgramStatus(codehash) {
		case progReady:
			return RunProgram(GetProgram(codehash), self.env, contract, input)
		case progUnknown:
			if ForceJit {
				// Create and compile program
				program = NewProgram(contract.Code)
				perr := CompileProgram(program)
				if perr == nil {
					return RunProgram(program, self.env, contract, input)
				}
				glog.V(logger.Info).Infoln("error compiling program", err)
			} else {
				// create and compile the program. Compilation
				// is done in a seperate goroutine
				program = NewProgram(contract.Code)
				go func() {
					err := CompileProgram(program)
					if err != nil {
						glog.V(logger.Info).Infoln("error compiling program", err)
						return
					}
				}()
			}
		}
	}

	var (
		caller     = contract.caller
		code       = contract.Code
		instrCount = 0

		op      OpCode          // current opcode
		mem     = NewMemory()   // bound memory
		stack   = newstack()    // local stack
		statedb = self.env.Db() // current state
		// For optimisation reason we're using uint64 as the program counter.
		// It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Pratically much less so feasible.
		pc = uint64(0) // program counter

		// jump evaluates and checks whether the given jump destination is a valid one
		// if valid move the `pc` otherwise return an error.
		jump = func(from uint64, to *big.Int) error {
			if !contract.jumpdests.has(codehash, code, to) {
				nop := contract.GetOp(to.Uint64())
				return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
			}

			pc = to.Uint64()

			return nil
		}

		newMemSize *big.Int
		cost       *big.Int
	)
	contract.Input = input

	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
	defer func() {
		if err != nil {
			self.log(pc, op, contract.Gas, cost, mem, stack, contract, err)
		}
	}()

//.........这里部分代码省略.........
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:101,代码来源:vm.go


注:本文中的github.com/expanse-project/go-expanse/crypto.Sha3Hash函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。