本文整理汇总了Golang中github.com/shiftcurrency/shift/core/types.Block.Hash方法的典型用法代码示例。如果您正苦于以下问题:Golang Block.Hash方法的具体用法?Golang Block.Hash怎么用?Golang Block.Hash使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/shiftcurrency/shift/core/types.Block
的用法示例。
在下文中一共展示了Block.Hash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: lowestPrice
// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
gasUsed := big.NewInt(0)
receipts := self.eth.BlockProcessor().GetBlockReceipts(block.Hash())
if len(receipts) > 0 {
if cgu := receipts[len(receipts)-1].CumulativeGasUsed; cgu != nil {
gasUsed = receipts[len(receipts)-1].CumulativeGasUsed
}
}
if new(big.Int).Mul(gasUsed, big.NewInt(100)).Cmp(new(big.Int).Mul(block.GasLimit(),
big.NewInt(int64(self.eth.GpoFullBlockRatio)))) < 0 {
// block is not full, could have posted a tx with MinGasPrice
return big.NewInt(0)
}
txs := block.Transactions()
if len(txs) == 0 {
return big.NewInt(0)
}
// block is full, find smallest gasPrice
minPrice := txs[0].GasPrice()
for i := 1; i < len(txs); i++ {
price := txs[i].GasPrice()
if price.Cmp(minPrice) < 0 {
minPrice = price
}
}
return minPrice
}
示例2: ApplyTransactions
func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
var (
receipts types.Receipts
totalUsedGas = big.NewInt(0)
err error
cumulativeSum = new(big.Int)
header = block.Header()
)
for i, tx := range txs {
statedb.StartRecord(tx.Hash(), block.Hash(), i)
receipt, txGas, err := self.ApplyTransaction(gp, statedb, header, tx, totalUsedGas, transientProcess)
if err != nil {
return nil, err
}
if err != nil {
glog.V(logger.Core).Infoln("TX err:", err)
}
receipts = append(receipts, receipt)
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
}
if block.GasUsed().Cmp(totalUsedGas) != 0 {
return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
}
if transientProcess {
go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
}
return receipts, err
}
示例3: enqueue
// enqueue schedules a new future import operation, if the block to be imported
// has not yet been seen.
func (f *Fetcher) enqueue(peer string, block *types.Block) {
hash := block.Hash()
// Ensure the peer isn't DOSing us
count := f.queues[peer] + 1
if count > blockLimit {
glog.V(logger.Debug).Infof("Peer %s: discarded block #%d [%x], exceeded allowance (%d)", peer, block.NumberU64(), hash.Bytes()[:4], blockLimit)
return
}
// Discard any past or too distant blocks
if dist := int64(block.NumberU64()) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist {
glog.V(logger.Debug).Infof("Peer %s: discarded block #%d [%x], distance %d", peer, block.NumberU64(), hash.Bytes()[:4], dist)
discardMeter.Mark(1)
return
}
// Schedule the block for future importing
if _, ok := f.queued[hash]; !ok {
op := &inject{
origin: peer,
block: block,
}
f.queues[peer] = count
f.queued[hash] = op
f.queue.Push(op, -float32(block.NumberU64()))
if glog.V(logger.Debug) {
glog.Infof("Peer %s: queued block #%d [%x], total %v", peer, block.NumberU64(), hash.Bytes()[:4], f.queue.Size())
}
}
}
示例4: BroadcastBlock
// BroadcastBlock will either propagate a block to a subset of it's peers, or
// will only announce it's availability (depending what's requested).
func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
hash := block.Hash()
peers := pm.peers.PeersWithoutBlock(hash)
// If propagation is requested, send to a subset of the peer
if propagate {
// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
var td *big.Int
if parent := pm.chainman.GetBlock(block.ParentHash()); parent != nil {
td = new(big.Int).Add(parent.Td, block.Difficulty())
} else {
glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
return
}
// Send the block to a subset of our peers
transfer := peers[:int(math.Sqrt(float64(len(peers))))]
for _, peer := range transfer {
peer.SendNewBlock(block, td)
}
glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
}
// Otherwise if the block is indeed in out own chain, announce it
if pm.chainman.HasBlock(hash) {
for _, peer := range peers {
peer.SendNewBlockHashes([]common.Hash{hash})
}
glog.V(logger.Detail).Infof("announced block %x to %d peers in %v", hash[:4], len(peers), time.Since(block.ReceivedAt))
}
}
示例5: SendNewBlock
// SendNewBlock propagates an entire block to a remote peer.
func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
propBlockOutPacketsMeter.Mark(1)
propBlockOutTrafficMeter.Mark(block.Size().Int64())
p.knownBlocks.Add(block.Hash())
return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
}
示例6: makeCurrent
// makeCurrent creates a new environment for the current cycle.
func (self *worker) makeCurrent(parent *types.Block, header *types.Header) {
state := state.New(parent.Root(), self.eth.ChainDb())
work := &Work{
state: state,
ancestors: set.New(),
family: set.New(),
uncles: set.New(),
header: header,
coinbase: state.GetOrNewStateObject(self.coinbase),
createdAt: time.Now(),
}
// when 08 is processed ancestors contain 07 (quick block)
for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
for _, uncle := range ancestor.Uncles() {
work.family.Add(uncle.Hash())
}
work.family.Add(ancestor.Hash())
work.ancestors.Add(ancestor.Hash())
}
accounts, _ := self.eth.AccountManager().Accounts()
// Keep track of transactions which return errors so they can be removed
work.remove = set.New()
work.tcount = 0
work.ignoredTransactors = set.New()
work.lowGasTransactors = set.New()
work.ownedAccounts = accountAddressesSet(accounts)
if self.current != nil {
work.localMinedBlocks = self.current.localMinedBlocks
}
self.current = work
}
示例7: blockRecovery
func blockRecovery(ctx *cli.Context) {
utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))
arg := ctx.Args().First()
if len(ctx.Args()) < 1 && len(arg) > 0 {
glog.Fatal("recover requires block number or hash")
}
cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
utils.CheckLegalese(cfg.DataDir)
blockDb, err := ethdb.NewLDBDatabase(filepath.Join(cfg.DataDir, "blockchain"), cfg.DatabaseCache)
if err != nil {
glog.Fatalln("could not open db:", err)
}
var block *types.Block
if arg[0] == '#' {
block = core.GetBlockByNumber(blockDb, common.String2Big(arg[1:]).Uint64())
} else {
block = core.GetBlockByHash(blockDb, common.HexToHash(arg))
}
if block == nil {
glog.Fatalln("block not found. Recovery failed")
}
err = core.WriteHead(blockDb, block)
if err != nil {
glog.Fatalln("block write err", err)
}
glog.Infof("Recovery succesful. New HEAD %x\n", block.Hash())
}
示例8: NewBlock
// Creates a new QML Block from a chain block
func NewBlock(block *types.Block) *Block {
if block == nil {
return &Block{}
}
ptxs := make([]*Transaction, len(block.Transactions()))
/*
for i, tx := range block.Transactions() {
ptxs[i] = NewTx(tx)
}
*/
txlist := common.NewList(ptxs)
puncles := make([]*Block, len(block.Uncles()))
/*
for i, uncle := range block.Uncles() {
puncles[i] = NewBlock(types.NewBlockWithHeader(uncle))
}
*/
ulist := common.NewList(puncles)
return &Block{
ref: block, Size: block.Size().String(),
Number: int(block.NumberU64()), GasUsed: block.GasUsed().String(),
GasLimit: block.GasLimit().String(), Hash: block.Hash().Hex(),
Transactions: txlist, Uncles: ulist,
Time: block.Time(),
Coinbase: block.Coinbase().Hex(),
PrevHash: block.ParentHash().Hex(),
Bloom: common.ToHex(block.Bloom().Bytes()),
Raw: block.String(),
}
}
示例9: removeBlock
func (bc *ChainManager) removeBlock(block *types.Block) {
if bc.sqlDB != nil {
bc.sqlDB.DeleteBlock(block)
}
bc.chainDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
}
示例10: WriteCanonNumber
// WriteCanonNumber writes the canonical hash for the given block
func WriteCanonNumber(db common.Database, block *types.Block) error {
key := append(blockNumPre, block.Number().Bytes()...)
err := db.Put(key, block.Hash().Bytes())
if err != nil {
return err
}
return nil
}
示例11: GetLogs
// GetLogs returns the logs of the given block. This method is using a two step approach
// where it tries to get it from the (updated) method which gets them from the receipts or
// the depricated way by re-processing the block.
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
receipts := GetBlockReceipts(sm.chainDb, block.Hash())
// coalesce logs
for _, receipt := range receipts {
logs = append(logs, receipt.Logs()...)
}
return logs, nil
}
示例12: WriteHead
// WriteHead force writes the current head
func WriteHead(db common.Database, block *types.Block) error {
err := WriteCanonNumber(db, block)
if err != nil {
return err
}
err = db.Put([]byte("LastBlock"), block.Hash().Bytes())
if err != nil {
return err
}
return nil
}
示例13: InsertBlock
func (self *SQLDB) InsertBlock(block *types.Block) {
tx, err := self.db.Begin()
if err != nil {
glog.V(logger.Error).Infoln("SQL DB Begin:", err)
return
}
stmtBlock, err := tx.Prepare(`insert or replace into shift_blocks(number, hash) values(?, ?)`)
if err != nil {
glog.V(logger.Error).Infoln("SQL DB:", err)
return
}
defer stmtBlock.Close()
stmtTrans, err := tx.Prepare(`insert or replace into shift_transactions(hash, blocknumber, sender, receiver) values(?, ?, ?, ?)`)
if err != nil {
glog.V(logger.Error).Infoln("SQL DB:", err)
return
}
defer stmtTrans.Close()
// block
_, err = stmtBlock.Exec(block.Number().Uint64(), block.Hash().Hex())
if err != nil {
glog.V(logger.Error).Infoln("SQL DB:", err)
tx.Rollback()
return
}
// transactions
for _, trans := range block.Transactions() {
sender, err := trans.From()
if err != nil {
glog.V(logger.Error).Infoln("SQL DB:", err)
continue
}
senderHex := sender.Hex()
receiver := trans.To()
receiverHex := ""
if receiver != nil {
receiverHex = receiver.Hex()
}
_, err = stmtTrans.Exec(trans.Hash().Hex(), block.Number().Uint64(), senderHex, receiverHex)
if err != nil {
glog.V(logger.Error).Infoln("SQL DB:", err)
tx.Rollback()
return
}
}
tx.Commit()
}
示例14: makeChain
// makeChain creates a chain of n blocks starting at but not including
// parent. the returned hash chain is ordered head->parent.
func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common.Hash]*types.Block) {
blocks := core.GenerateChain(parent, testdb, n, func(i int, gen *core.BlockGen) {
gen.SetCoinbase(common.Address{seed})
})
hashes := make([]common.Hash, n+1)
hashes[len(hashes)-1] = parent.Hash()
blockm := make(map[common.Hash]*types.Block, n+1)
blockm[parent.Hash()] = parent
for i, b := range blocks {
hashes[len(hashes)-i-2] = b.Hash()
blockm[b.Hash()] = b
}
return hashes, blockm
}
示例15: Process
// Process block will attempt to process the given block's transactions and applies them
// on top of the block's parent state (given it exists) and will return wether it was
// successful or not.
func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, receipts types.Receipts, err error) {
// Processing a blocks may never happen simultaneously
sm.mutex.Lock()
defer sm.mutex.Unlock()
if sm.bc.HasBlock(block.Hash()) {
return nil, nil, &KnownBlockError{block.Number(), block.Hash()}
}
if !sm.bc.HasBlock(block.ParentHash()) {
return nil, nil, ParentError(block.ParentHash())
}
parent := sm.bc.GetBlock(block.ParentHash())
return sm.processWithParent(block, parent)
}