github.com/abschain-develop/go-abs@v2.0.3+incompatible/core/types/block.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package types contains data types related to Ethereum consensus. 18 package types 19 20 import ( 21 "encoding/binary" 22 "io" 23 "math/big" 24 "sort" 25 "sync/atomic" 26 "time" 27 "unsafe" 28 29 "github.com/abschain-develop/go-abs/common" 30 "github.com/abschain-develop/go-abs/common/hexutil" 31 "github.com/abschain-develop/go-abs/rlp" 32 "golang.org/x/crypto/sha3" 33 ) 34 35 var ( 36 EmptyRootHash = DeriveSha(Transactions{}) 37 EmptyUncleHash = CalcUncleHash(nil) 38 ) 39 40 // A BlockNonce is a 64-bit hash which proves (combined with the 41 // mix-hash) that a sufficient amount of computation has been carried 42 // out on a block. 43 type BlockNonce [8]byte 44 45 // EncodeNonce converts the given integer to a block nonce. 46 func EncodeNonce(i uint64) BlockNonce { 47 var n BlockNonce 48 binary.BigEndian.PutUint64(n[:], i) 49 return n 50 } 51 52 // Uint64 returns the integer value of a block nonce. 53 func (n BlockNonce) Uint64() uint64 { 54 return binary.BigEndian.Uint64(n[:]) 55 } 56 57 // MarshalText encodes n as a hex string with 0x prefix. 58 func (n BlockNonce) MarshalText() ([]byte, error) { 59 return hexutil.Bytes(n[:]).MarshalText() 60 } 61 62 // UnmarshalText implements encoding.TextUnmarshaler. 63 func (n *BlockNonce) UnmarshalText(input []byte) error { 64 return hexutil.UnmarshalFixedText("BlockNonce", input, n[:]) 65 } 66 67 //go:generate gencodec -type Header -field-override headerMarshaling -out gen_header_json.go 68 69 // Header represents a block header in the Ethereum blockchain. 70 type Header struct { 71 ParentHash common.Hash `json:"parentHash" gencodec:"required"` 72 UncleHash common.Hash `json:"sha3Uncles" gencodec:"required"` 73 Coinbase common.Address `json:"miner" gencodec:"required"` 74 Root common.Hash `json:"stateRoot" gencodec:"required"` 75 TxHash common.Hash `json:"transactionsRoot" gencodec:"required"` 76 ReceiptHash common.Hash `json:"receiptsRoot" gencodec:"required"` 77 Bloom Bloom `json:"logsBloom" gencodec:"required"` 78 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 79 Number *big.Int `json:"number" gencodec:"required"` 80 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 81 GasUsed uint64 `json:"gasUsed" gencodec:"required"` 82 Time uint64 `json:"timestamp" gencodec:"required"` 83 Extra []byte `json:"extraData" gencodec:"required"` 84 MixDigest common.Hash `json:"mixHash"` 85 Nonce BlockNonce `json:"nonce"` 86 } 87 88 // field type overrides for gencodec 89 type headerMarshaling struct { 90 Difficulty *hexutil.Big 91 Number *hexutil.Big 92 GasLimit hexutil.Uint64 93 GasUsed hexutil.Uint64 94 Time hexutil.Uint64 95 Extra hexutil.Bytes 96 Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON 97 } 98 99 // Hash returns the block hash of the header, which is simply the keccak256 hash of its 100 // RLP encoding. 101 func (h *Header) Hash() common.Hash { 102 return rlpHash(h) 103 } 104 105 // Size returns the approximate memory used by all internal contents. It is used 106 // to approximate and limit the memory consumption of various caches. 107 func (h *Header) Size() common.StorageSize { 108 return common.StorageSize(unsafe.Sizeof(*h)) + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen())/8) 109 } 110 111 func rlpHash(x interface{}) (h common.Hash) { 112 hw := sha3.NewLegacyKeccak256() 113 rlp.Encode(hw, x) 114 hw.Sum(h[:0]) 115 return h 116 } 117 118 // Body is a simple (mutable, non-safe) data container for storing and moving 119 // a block's data contents (transactions and uncles) together. 120 type Body struct { 121 Transactions []*Transaction 122 Uncles []*Header 123 } 124 125 // Block represents an entire block in the Ethereum blockchain. 126 type Block struct { 127 header *Header 128 uncles []*Header 129 transactions Transactions 130 131 // caches 132 hash atomic.Value 133 size atomic.Value 134 135 // Td is used by package core to store the total difficulty 136 // of the chain up to and including the block. 137 td *big.Int 138 139 // These fields are used by package eth to track 140 // inter-peer block relay. 141 ReceivedAt time.Time 142 ReceivedFrom interface{} 143 } 144 145 // DeprecatedTd is an old relic for extracting the TD of a block. It is in the 146 // code solely to facilitate upgrading the database from the old format to the 147 // new, after which it should be deleted. Do not use! 148 func (b *Block) DeprecatedTd() *big.Int { 149 return b.td 150 } 151 152 // [deprecated by eth/63] 153 // StorageBlock defines the RLP encoding of a Block stored in the 154 // state database. The StorageBlock encoding contains fields that 155 // would otherwise need to be recomputed. 156 type StorageBlock Block 157 158 // "external" block encoding. used for eth protocol, etc. 159 type extblock struct { 160 Header *Header 161 Txs []*Transaction 162 Uncles []*Header 163 } 164 165 // [deprecated by eth/63] 166 // "storage" block encoding. used for database. 167 type storageblock struct { 168 Header *Header 169 Txs []*Transaction 170 Uncles []*Header 171 TD *big.Int 172 } 173 174 // NewBlock creates a new block. The input data is copied, 175 // changes to header and to the field values will not affect the 176 // block. 177 // 178 // The values of TxHash, UncleHash, ReceiptHash and Bloom in header 179 // are ignored and set to values derived from the given txs, uncles 180 // and receipts. 181 func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block { 182 b := &Block{header: CopyHeader(header), td: new(big.Int)} 183 184 // TODO: panic if len(txs) != len(receipts) 185 if len(txs) == 0 { 186 b.header.TxHash = EmptyRootHash 187 } else { 188 b.header.TxHash = DeriveSha(Transactions(txs)) 189 b.transactions = make(Transactions, len(txs)) 190 copy(b.transactions, txs) 191 } 192 193 if len(receipts) == 0 { 194 b.header.ReceiptHash = EmptyRootHash 195 } else { 196 b.header.ReceiptHash = DeriveSha(Receipts(receipts)) 197 b.header.Bloom = CreateBloom(receipts) 198 } 199 200 if len(uncles) == 0 { 201 b.header.UncleHash = EmptyUncleHash 202 } else { 203 b.header.UncleHash = CalcUncleHash(uncles) 204 b.uncles = make([]*Header, len(uncles)) 205 for i := range uncles { 206 b.uncles[i] = CopyHeader(uncles[i]) 207 } 208 } 209 210 return b 211 } 212 213 // NewBlockWithHeader creates a block with the given header data. The 214 // header data is copied, changes to header and to the field values 215 // will not affect the block. 216 func NewBlockWithHeader(header *Header) *Block { 217 return &Block{header: CopyHeader(header)} 218 } 219 220 // CopyHeader creates a deep copy of a block header to prevent side effects from 221 // modifying a header variable. 222 func CopyHeader(h *Header) *Header { 223 cpy := *h 224 if cpy.Difficulty = new(big.Int); h.Difficulty != nil { 225 cpy.Difficulty.Set(h.Difficulty) 226 } 227 if cpy.Number = new(big.Int); h.Number != nil { 228 cpy.Number.Set(h.Number) 229 } 230 if len(h.Extra) > 0 { 231 cpy.Extra = make([]byte, len(h.Extra)) 232 copy(cpy.Extra, h.Extra) 233 } 234 return &cpy 235 } 236 237 // DecodeRLP decodes the Ethereum 238 func (b *Block) DecodeRLP(s *rlp.Stream) error { 239 var eb extblock 240 _, size, _ := s.Kind() 241 if err := s.Decode(&eb); err != nil { 242 return err 243 } 244 b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs 245 b.size.Store(common.StorageSize(rlp.ListSize(size))) 246 return nil 247 } 248 249 // EncodeRLP serializes b into the Ethereum RLP block format. 250 func (b *Block) EncodeRLP(w io.Writer) error { 251 return rlp.Encode(w, extblock{ 252 Header: b.header, 253 Txs: b.transactions, 254 Uncles: b.uncles, 255 }) 256 } 257 258 // [deprecated by eth/63] 259 func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { 260 var sb storageblock 261 if err := s.Decode(&sb); err != nil { 262 return err 263 } 264 b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD 265 return nil 266 } 267 268 // TODO: copies 269 270 func (b *Block) Uncles() []*Header { return b.uncles } 271 func (b *Block) Transactions() Transactions { return b.transactions } 272 273 func (b *Block) Transaction(hash common.Hash) *Transaction { 274 for _, transaction := range b.transactions { 275 if transaction.Hash() == hash { 276 return transaction 277 } 278 } 279 return nil 280 } 281 282 func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } 283 func (b *Block) GasLimit() uint64 { return b.header.GasLimit } 284 func (b *Block) GasUsed() uint64 { return b.header.GasUsed } 285 func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } 286 func (b *Block) Time() uint64 { return b.header.Time } 287 288 func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } 289 func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } 290 func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } 291 func (b *Block) Bloom() Bloom { return b.header.Bloom } 292 func (b *Block) Coinbase() common.Address { return b.header.Coinbase } 293 func (b *Block) Root() common.Hash { return b.header.Root } 294 func (b *Block) ParentHash() common.Hash { return b.header.ParentHash } 295 func (b *Block) TxHash() common.Hash { return b.header.TxHash } 296 func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } 297 func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } 298 func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } 299 300 func (b *Block) Header() *Header { return CopyHeader(b.header) } 301 302 // Body returns the non-header content of the block. 303 func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} } 304 305 // Size returns the true RLP encoded storage size of the block, either by encoding 306 // and returning it, or returning a previsouly cached value. 307 func (b *Block) Size() common.StorageSize { 308 if size := b.size.Load(); size != nil { 309 return size.(common.StorageSize) 310 } 311 c := writeCounter(0) 312 rlp.Encode(&c, b) 313 b.size.Store(common.StorageSize(c)) 314 return common.StorageSize(c) 315 } 316 317 type writeCounter common.StorageSize 318 319 func (c *writeCounter) Write(b []byte) (int, error) { 320 *c += writeCounter(len(b)) 321 return len(b), nil 322 } 323 324 func CalcUncleHash(uncles []*Header) common.Hash { 325 return rlpHash(uncles) 326 } 327 328 // WithSeal returns a new block with the data from b but the header replaced with 329 // the sealed one. 330 func (b *Block) WithSeal(header *Header) *Block { 331 cpy := *header 332 333 return &Block{ 334 header: &cpy, 335 transactions: b.transactions, 336 uncles: b.uncles, 337 } 338 } 339 340 // WithBody returns a new block with the given transaction and uncle contents. 341 func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block { 342 block := &Block{ 343 header: CopyHeader(b.header), 344 transactions: make([]*Transaction, len(transactions)), 345 uncles: make([]*Header, len(uncles)), 346 } 347 copy(block.transactions, transactions) 348 for i := range uncles { 349 block.uncles[i] = CopyHeader(uncles[i]) 350 } 351 return block 352 } 353 354 // Hash returns the keccak256 hash of b's header. 355 // The hash is computed on the first call and cached thereafter. 356 func (b *Block) Hash() common.Hash { 357 if hash := b.hash.Load(); hash != nil { 358 return hash.(common.Hash) 359 } 360 v := b.header.Hash() 361 b.hash.Store(v) 362 return v 363 } 364 365 type Blocks []*Block 366 367 type BlockBy func(b1, b2 *Block) bool 368 369 func (self BlockBy) Sort(blocks Blocks) { 370 bs := blockSorter{ 371 blocks: blocks, 372 by: self, 373 } 374 sort.Sort(bs) 375 } 376 377 type blockSorter struct { 378 blocks Blocks 379 by func(b1, b2 *Block) bool 380 } 381 382 func (self blockSorter) Len() int { return len(self.blocks) } 383 func (self blockSorter) Swap(i, j int) { 384 self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i] 385 } 386 func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) } 387 388 func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }