本文整理汇总了Golang中github.com/expanse-project/go-expanse/common.Hash类的典型用法代码示例。如果您正苦于以下问题:Golang Hash类的具体用法?Golang Hash怎么用?Golang Hash使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Hash类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: WriteHeadFastBlockHash
// WriteHeadFastBlockHash stores the fast head block's hash.
func WriteHeadFastBlockHash(db ethdb.Database, hash common.Hash) error {
if err := db.Put(headFastKey, hash.Bytes()); err != nil {
glog.Fatalf("failed to store last fast block's hash into database: %v", err)
return err
}
return nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:8,代码来源:database_util.go
示例2: HashToUrl
// HashToUrl(contenthash) resolves the url for contenthash using UrlHint
// resolution is costless non-transactional
// implemented as direct retrieval from db
// if we use content addressed storage, this step is no longer necessary
func (self *Registrar) HashToUrl(chash common.Hash) (uri string, err error) {
if zero.MatchString(UrlHintAddr) {
return "", fmt.Errorf("UrlHint address is not set")
}
// look up in URL reg
var str string = " "
var idx uint32
for len(str) > 0 {
mapaddr := storageMapping(storageIdx2Addr(1), chash[:])
key := storageAddress(storageFixedArray(mapaddr, storageIdx2Addr(idx)))
hex := self.backend.StorageAt(UrlHintAddr[2:], key)
str = string(common.Hex2Bytes(hex[2:]))
l := 0
for (l < len(str)) && (str[l] == 0) {
l++
}
str = str[l:]
uri = uri + str
idx++
}
if len(uri) == 0 {
err = fmt.Errorf("HashToUrl: URL hint not found for '%v'", chash.Hex())
}
return
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:31,代码来源:registrar.go
示例3: AddSubTrie
// AddSubTrie registers a new trie to the sync code, rooted at the designated parent.
func (s *TrieSync) AddSubTrie(root common.Hash, depth int, parent common.Hash, callback TrieSyncLeafCallback) {
// Short circuit if the trie is empty or already known
if root == emptyRoot {
return
}
blob, _ := s.database.Get(root.Bytes())
if local, err := decodeNode(blob); local != nil && err == nil {
return
}
// Assemble the new sub-trie sync request
node := node(hashNode(root.Bytes()))
req := &request{
object: &node,
hash: root,
depth: depth,
callback: callback,
}
// If this sub-trie has a designated parent, link them together
if parent != (common.Hash{}) {
ancestor := s.requests[parent]
if ancestor == nil {
panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
}
ancestor.deps++
req.parents = append(req.parents, ancestor)
}
s.schedule(req)
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:29,代码来源:sync.go
示例4: GetTransaction
// GetTransaction retrieves a specific transaction from the database, along with
// its added positional metadata.
func GetTransaction(db ethdb.Database, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
// Retrieve the transaction itself from the database
data, _ := db.Get(hash.Bytes())
if len(data) == 0 {
return nil, common.Hash{}, 0, 0
}
var tx types.Transaction
if err := rlp.DecodeBytes(data, &tx); err != nil {
return nil, common.Hash{}, 0, 0
}
// Retrieve the blockchain positional metadata
data, _ = db.Get(append(hash.Bytes(), txMetaSuffix...))
if len(data) == 0 {
return nil, common.Hash{}, 0, 0
}
var meta struct {
BlockHash common.Hash
BlockIndex uint64
Index uint64
}
if err := rlp.DecodeBytes(data, &meta); err != nil {
return nil, common.Hash{}, 0, 0
}
return &tx, meta.BlockHash, meta.BlockIndex, meta.Index
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:27,代码来源:database_util.go
示例5: VerifyProof
// VerifyProof checks merkle proofs. The given proof must contain the
// value for key in a trie with the given root hash. VerifyProof
// returns an error if the proof contains invalid trie nodes or the
// wrong value.
func VerifyProof(rootHash common.Hash, key []byte, proof []rlp.RawValue) (value []byte, err error) {
key = compactHexDecode(key)
sha := sha3.NewKeccak256()
wantHash := rootHash.Bytes()
for i, buf := range proof {
sha.Reset()
sha.Write(buf)
if !bytes.Equal(sha.Sum(nil), wantHash) {
return nil, fmt.Errorf("bad proof node %d: hash mismatch", i)
}
n, err := decodeNode(wantHash, buf)
if err != nil {
return nil, fmt.Errorf("bad proof node %d: %v", i, err)
}
keyrest, cld := get(n, key)
switch cld := cld.(type) {
case nil:
if i != len(proof)-1 {
return nil, fmt.Errorf("key mismatch at proof node %d", i)
} else {
// The trie doesn't contain the key.
return nil, nil
}
case hashNode:
key = keyrest
wantHash = cld
case valueNode:
if i != len(proof)-1 {
return nil, errors.New("additional nodes at end of proof")
}
return cld, nil
}
}
return nil, errors.New("unexpected end of proof")
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:39,代码来源:proof.go
示例6: WriteCanonicalHash
// WriteCanonicalHash stores the canonical hash for the given block number.
func WriteCanonicalHash(db ethdb.Database, hash common.Hash, number uint64) error {
key := append(blockNumPrefix, big.NewInt(int64(number)).Bytes()...)
if err := db.Put(key, hash.Bytes()); err != nil {
glog.Fatalf("failed to store number to hash mapping into database: %v", err)
return err
}
return nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:9,代码来源:database_util.go
示例7: GetTd
// GetTd retrieves a block's total difficulty corresponding to the hash, nil if
// none found.
func GetTd(db ethdb.Database, hash common.Hash) *big.Int {
data, _ := db.Get(append(append(blockPrefix, hash.Bytes()...), tdSuffix...))
if len(data) == 0 {
return nil
}
td := new(big.Int)
if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
glog.V(logger.Error).Infof("invalid block total difficulty RLP for hash %x: %v", hash, err)
return nil
}
return td
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:14,代码来源:database_util.go
示例8: GetState
func (self *StateObject) GetState(key common.Hash) common.Hash {
strkey := key.Str()
value, exists := self.storage[strkey]
if !exists {
value = self.getAddr(key)
if (value != common.Hash{}) {
self.storage[strkey] = value
}
}
return value
}
开发者ID:5mil,项目名称:go-expanse,代码行数:12,代码来源:state_object.go
示例9: WriteTd
// WriteTd serializes the total difficulty of a block into the database.
func WriteTd(db ethdb.Database, hash common.Hash, td *big.Int) error {
data, err := rlp.EncodeToBytes(td)
if err != nil {
return err
}
key := append(append(blockPrefix, hash.Bytes()...), tdSuffix...)
if err := db.Put(key, data); err != nil {
glog.Fatalf("failed to store block total difficulty into database: %v", err)
return err
}
glog.V(logger.Debug).Infof("stored block total difficulty [%x…]: %v", hash.Bytes()[:4], td)
return nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:14,代码来源:database_util.go
示例10: New
// New creates a trie with an existing root node from db.
//
// If root is the zero hash or the sha3 hash of an empty string, the
// trie is initially empty and does not require a database. Otherwise,
// New will panics if db is nil or root does not exist in the
// database. Accessing the trie loads nodes from db on demand.
func New(root common.Hash, db Database) (*Trie, error) {
trie := &Trie{db: db}
if (root != common.Hash{}) && root != emptyRoot {
if db == nil {
panic("trie.New: cannot use existing root without a database")
}
if v, _ := trie.db.Get(root[:]); len(v) == 0 {
return nil, ErrMissingRoot
}
trie.root = hashNode(root.Bytes())
}
return trie, nil
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:19,代码来源:trie.go
示例11: WriteBody
// WriteBody serializes the body of a block into the database.
func WriteBody(db ethdb.Database, hash common.Hash, body *types.Body) error {
data, err := rlp.EncodeToBytes(body)
if err != nil {
return err
}
key := append(append(blockPrefix, hash.Bytes()...), bodySuffix...)
if err := db.Put(key, data); err != nil {
glog.Fatalf("failed to store block body into database: %v", err)
return err
}
glog.V(logger.Debug).Infof("stored block body [%x…]", hash.Bytes()[:4])
return nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:14,代码来源:database_util.go
示例12: checkStateConsistency
// checkStateConsistency checks that all nodes in a state trie are indeed present.
func checkStateConsistency(db ethdb.Database, root common.Hash) error {
// Create and iterate a state trie rooted in a sub-node
if _, err := db.Get(root.Bytes()); err != nil {
return nil // Consider a non existent state consistent
}
state, err := New(root, db)
if err != nil {
return err
}
it := NewNodeIterator(state)
for it.Next() {
}
return it.Error
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:15,代码来源:sync_test.go
示例13: GetState
// GetState returns the storage value at the given address from either the cache
// or the trie
func (self *StateObject) GetState(ctx context.Context, key common.Hash) (common.Hash, error) {
strkey := key.Str()
value, exists := self.storage[strkey]
if !exists {
var err error
value, err = self.getAddr(ctx, key)
if err != nil {
return common.Hash{}, err
}
if (value != common.Hash{}) {
self.storage[strkey] = value
}
}
return value, nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:18,代码来源:state_object.go
示例14: doSign
func (self *XEth) doSign(from common.Address, hash common.Hash, didUnlock bool) ([]byte, error) {
sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from}, hash.Bytes())
if err == accounts.ErrLocked {
if didUnlock {
return nil, fmt.Errorf("signer account still locked after successful unlock")
}
if !self.frontend.UnlockAccount(from.Bytes()) {
return nil, fmt.Errorf("could not unlock signer account")
}
// retry signing, the account should now be unlocked.
return self.doSign(from, hash, true)
} else if err != nil {
return nil, err
}
return sig, nil
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:16,代码来源:xeth.go
示例15: HashToHash
// HashToHash(key) resolves contenthash for key (a hash) using HashReg
// resolution is costless non-transactional
// implemented as direct retrieval from db
func (self *Registrar) HashToHash(khash common.Hash) (chash common.Hash, err error) {
if zero.MatchString(HashRegAddr) {
return common.Hash{}, fmt.Errorf("HashReg address is not set")
}
// look up in hashReg
at := HashRegAddr[2:]
key := storageAddress(storageMapping(storageIdx2Addr(1), khash[:]))
hash := self.backend.StorageAt(at, key)
if hash == "0x0" || len(hash) < 3 || (hash == common.Hash{}.Hex()) {
err = fmt.Errorf("HashToHash: content hash not found for '%v'", khash.Hex())
return
}
copy(chash[:], common.Hex2BytesFixed(hash[2:], 32))
return
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:20,代码来源:registrar.go
示例16: WriteBlockReceipts
// WriteBlockReceipts stores all the transaction receipts belonging to a block
// as a single receipt slice. This is used during chain reorganisations for
// rescheduling dropped transactions.
func WriteBlockReceipts(db ethdb.Database, hash common.Hash, receipts types.Receipts) error {
// Convert the receipts into their storage form and serialize them
storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
for i, receipt := range receipts {
storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
}
bytes, err := rlp.EncodeToBytes(storageReceipts)
if err != nil {
return err
}
// Store the flattened receipt slice
if err := db.Put(append(blockReceiptsPrefix, hash.Bytes()...), bytes); err != nil {
glog.Fatalf("failed to store block receipts into database: %v", err)
return err
}
glog.V(logger.Debug).Infof("stored block receipts [%x…]", hash.Bytes()[:4])
return nil
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:21,代码来源:database_util.go
示例17: AddRawEntry
// AddRawEntry schedules the direct retrieval of a state entry that should not be
// interpreted as a trie node, but rather accepted and stored into the database
// as is. This method's goal is to support misc state metadata retrievals (e.g.
// contract code).
func (s *TrieSync) AddRawEntry(hash common.Hash, depth int, parent common.Hash) {
// Short circuit if the entry is empty or already known
if hash == emptyState {
return
}
if blob, _ := s.database.Get(hash.Bytes()); blob != nil {
return
}
// Assemble the new sub-trie sync request
req := &request{
hash: hash,
depth: depth,
}
// If this sub-trie has a designated parent, link them together
if parent != (common.Hash{}) {
ancestor := s.requests[parent]
if ancestor == nil {
panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
}
ancestor.deps++
req.parents = append(req.parents, ancestor)
}
s.schedule(req)
}
开发者ID:Cisko-Rijken,项目名称:go-expanse,代码行数:28,代码来源:sync.go
示例18: handleMsg
// handleMsg is invoked whenever an inbound message is received from a remote
// peer. The remote connection is torn down upon returning any error.
func (pm *ProtocolManager) handleMsg(p *peer) error {
// Read the next message from the remote peer, and ensure it's fully consumed
msg, err := p.rw.ReadMsg()
if err != nil {
return err
}
if msg.Size > ProtocolMaxMsgSize {
return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
}
defer msg.Discard()
// Handle the message depending on its contents
switch {
case msg.Code == StatusMsg:
// Status messages should never arrive after the handshake
return errResp(ErrExtraStatusMsg, "uncontrolled status message")
// Block header query, collect the requested headers and reply
case msg.Code == GetBlockHeadersMsg:
// Decode the complex header query
var query getBlockHeadersData
if err := msg.Decode(&query); err != nil {
return errResp(ErrDecode, "%v: %v", msg, err)
}
hashMode := query.Origin.Hash != (common.Hash{})
// Gather headers until the fetch or network limits is reached
var (
bytes common.StorageSize
headers []*types.Header
unknown bool
)
for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
// Retrieve the next header satisfying the query
var origin *types.Header
if hashMode {
origin = pm.blockchain.GetHeader(query.Origin.Hash)
} else {
origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
}
if origin == nil {
break
}
headers = append(headers, origin)
bytes += estHeaderRlpSize
// Advance to the next header of the query
switch {
case query.Origin.Hash != (common.Hash{}) && query.Reverse:
// Hash based traversal towards the genesis block
for i := 0; i < int(query.Skip)+1; i++ {
if header := pm.blockchain.GetHeader(query.Origin.Hash); header != nil {
query.Origin.Hash = header.ParentHash
} else {
unknown = true
break
}
}
case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
// Hash based traversal towards the leaf block
var (
current = origin.Number.Uint64()
next = current + query.Skip + 1
)
if next <= current {
infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ")
glog.V(logger.Warn).Infof("%v: GetBlockHeaders skip overflow attack (current %v, skip %v, next %v)\nMalicious peer infos: %s", p, current, query.Skip, next, infos)
unknown = true
} else {
if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
query.Origin.Hash = header.Hash()
} else {
unknown = true
}
} else {
unknown = true
}
}
case query.Reverse:
// Number based traversal towards the genesis block
if query.Origin.Number >= query.Skip+1 {
query.Origin.Number -= (query.Skip + 1)
} else {
unknown = true
}
case !query.Reverse:
// Number based traversal towards the leaf block
query.Origin.Number += (query.Skip + 1)
}
}
return p.SendBlockHeaders(headers)
case msg.Code == BlockHeadersMsg:
// A batch of headers arrived to one of our previous requests
var headers []*types.Header
if err := msg.Decode(&headers); err != nil {
//.........这里部分代码省略.........
开发者ID:expanse-project,项目名称:go-expanse,代码行数:101,代码来源:handler.go
示例19: SetState
func (self *StateObject) SetState(k, value common.Hash) {
self.storage[k.Str()] = value
self.dirty = true
}
开发者ID:5mil,项目名称:go-expanse,代码行数:4,代码来源:state_object.go
示例20: banBlocks
// banBlocks retrieves a batch of blocks from a peer feeding us invalid hashes,
// and bans the head of the retrieved batch.
//
// This method only fetches one single batch as the goal is not ban an entire
// (potentially long) invalid chain - wasting a lot of time in the meanwhile -,
// but rather to gradually build up a blacklist if the peer keeps reconnecting.
func (d *Downloader) banBlocks(peerId string, head common.Hash) error {
glog.V(logger.Debug).Infof("Banning a batch out of %d blocks from %s", d.queue.Pending(), peerId)
// Ask the peer being banned for a batch of blocks from the banning point
peer := d.peers.Peer(peerId)
if peer == nil {
return nil
}
request := d.queue.Reserve(peer, MaxBlockFetch)
if request == nil {
return nil
}
if err := peer.Fetch(request); err != nil {
return err
}
// Wait a bit for the reply to arrive, and ban if done so
timeout := time.After(blockHardTTL)
for {
select {
case <-d.cancelCh:
return errCancelBlockFetch
case <-timeout:
return errTimeout
case <-d.hashCh:
// Out of bounds hashes received, ignore them
case blockPack := <-d.blockCh:
blocks := blockPack.blocks
// Short circuit if it's a stale cross check
if len(blocks) == 1 {
block := blocks[0]
if _, ok := d.checks[block.Hash()]; ok {
delete(d.checks, block.Hash())
break
}
}
// Short circuit if it's not from the peer being banned
if blockPack.peerId != peerId {
break
}
// Short circuit if no blocks were returned
if len(blocks) == 0 {
return errors.New("no blocks returned to ban")
}
// Reconstruct the original chain order and ensure we're banning the correct blocks
types.BlockBy(types.Number).Sort(blocks)
if bytes.Compare(blocks[0].Hash().Bytes(), head.Bytes()) != 0 {
return errors.New("head block not the banned one")
}
index := 0
for _, block := range blocks[1:] {
if bytes.Compare(block.ParentHash().Bytes(), blocks[index].Hash().Bytes()) != 0 {
break
}
index++
}
// Ban the head hash and phase out any excess
d.banned.Add(blocks[index].Hash())
for d.banned.Size() > maxBannedHashes {
var evacuate common.Hash
d.banned.Each(func(item interface{}) bool {
// Skip any hard coded bans
if core.BadHashes[item.(common.Hash)] {
return true
}
evacuate = item.(common.Hash)
return false
})
d.banned.Remove(evacuate)
}
glog.V(logger.Debug).Infof("Banned %d blocks from: %s", index+1, peerId)
return nil
}
}
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:85,代码来源:downloader.go
注:本文中的github.com/expanse-project/go-expanse/common.Hash类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论