neo-go/pkg/core/block/block.go

242 lines
6.7 KiB
Go
Raw Normal View History

package block
2018-01-30 10:56:36 +00:00
import (
"encoding/json"
"errors"
"math"
"math/big"
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
2018-01-30 10:56:36 +00:00
)
const (
// MaxTransactionsPerBlock is the maximum number of transactions per block.
2021-03-01 13:49:24 +00:00
MaxTransactionsPerBlock = math.MaxUint16
)
// ErrMaxContentsPerBlock is returned when the maximum number of contents per block is reached.
var ErrMaxContentsPerBlock = errors.New("the number of contents exceeds the maximum number of contents per block")
2021-03-15 10:00:04 +00:00
var expectedHeaderSizeWithEmptyWitness int
func init() {
expectedHeaderSizeWithEmptyWitness = io.GetVarSize(new(Header))
}
// Block represents one block in the chain.
type Block struct {
// The base of the block.
2021-03-01 13:44:47 +00:00
Header
// Transaction list.
Transactions []*transaction.Transaction
// True if this block is created from trimmed data.
Trimmed bool
}
// auxBlockOut is used for JSON i/o.
type auxBlockOut struct {
2021-03-01 12:20:27 +00:00
Transactions []*transaction.Transaction `json:"tx"`
2018-01-30 10:56:36 +00:00
}
// auxBlockIn is used for JSON i/o.
type auxBlockIn struct {
2021-03-01 12:20:27 +00:00
Transactions []json.RawMessage `json:"tx"`
}
// ComputeMerkleRoot computes Merkle tree root hash based on actual block's data.
func (b *Block) ComputeMerkleRoot() util.Uint256 {
2021-03-01 12:20:27 +00:00
hashes := make([]util.Uint256, len(b.Transactions))
for i, tx := range b.Transactions {
2021-03-01 12:20:27 +00:00
hashes[i] = tx.Hash()
}
return hash.CalcMerkleRoot(hashes)
}
// RebuildMerkleRoot rebuilds the merkleroot of the block.
func (b *Block) RebuildMerkleRoot() {
b.MerkleRoot = b.ComputeMerkleRoot()
}
// NewTrimmedFromReader returns a new block from trimmed data.
// This is commonly used to create a block from stored data.
// Blocks created from trimmed data will have their Trimmed field
// set to true.
func NewTrimmedFromReader(stateRootEnabled bool, br *io.BinReader) (*Block, error) {
block := &Block{
2021-03-01 13:44:47 +00:00
Header: Header{
StateRootEnabled: stateRootEnabled,
},
Trimmed: true,
}
2021-03-01 13:44:47 +00:00
block.Header.DecodeBinary(br)
lenHashes := br.ReadVarUint()
2021-03-01 13:49:24 +00:00
if lenHashes > MaxTransactionsPerBlock {
return nil, ErrMaxContentsPerBlock
}
if lenHashes > 0 {
2021-03-01 12:20:27 +00:00
block.Transactions = make([]*transaction.Transaction, lenHashes)
for i := range lenHashes {
var hash util.Uint256
hash.DecodeBinary(br)
block.Transactions[i] = transaction.NewTrimmedTX(hash)
}
}
return block, br.Err
}
// New creates a new blank block with proper state root setting.
func New(stateRootEnabled bool) *Block {
return &Block{
2021-03-01 13:44:47 +00:00
Header: Header{
StateRootEnabled: stateRootEnabled,
},
}
}
// EncodeTrimmed writes trimmed representation of the block data into w. Trimmed blocks
// do not store complete transactions, instead they only store their hashes.
func (b *Block) EncodeTrimmed(w *io.BinWriter) {
b.Header.EncodeBinary(w)
w.WriteVarUint(uint64(len(b.Transactions)))
for _, tx := range b.Transactions {
h := tx.Hash()
h.EncodeBinary(w)
}
}
// DecodeBinary decodes the block from the given BinReader, implementing
// Serializable interface.
func (b *Block) DecodeBinary(br *io.BinReader) {
2021-03-01 13:44:47 +00:00
b.Header.DecodeBinary(br)
contentsCount := br.ReadVarUint()
2021-03-01 13:49:24 +00:00
if contentsCount > MaxTransactionsPerBlock {
br.Err = ErrMaxContentsPerBlock
return
}
2021-03-01 12:20:27 +00:00
txes := make([]*transaction.Transaction, contentsCount)
for i := range txes {
tx := &transaction.Transaction{}
tx.DecodeBinary(br)
txes[i] = tx
}
b.Transactions = txes
if br.Err != nil {
return
}
}
// EncodeBinary encodes the block to the given BinWriter, implementing
// Serializable interface.
func (b *Block) EncodeBinary(bw *io.BinWriter) {
2021-03-01 13:44:47 +00:00
b.Header.EncodeBinary(bw)
2021-03-01 12:20:27 +00:00
bw.WriteVarUint(uint64(len(b.Transactions)))
for i := range b.Transactions {
b.Transactions[i].EncodeBinary(bw)
}
}
// MarshalJSON implements the json.Marshaler interface.
func (b Block) MarshalJSON() ([]byte, error) {
abo := auxBlockOut{
2021-03-01 12:20:27 +00:00
Transactions: b.Transactions,
}
// `"tx": []` (C#) vs `"tx": null` (default Go when missing any transactions)
if abo.Transactions == nil {
abo.Transactions = []*transaction.Transaction{}
}
auxb, err := json.Marshal(abo)
if err != nil {
return nil, err
}
2021-03-01 13:44:47 +00:00
baseBytes, err := json.Marshal(b.Header)
if err != nil {
return nil, err
}
// Stitch them together.
if baseBytes[len(baseBytes)-1] != '}' || auxb[0] != '{' {
return nil, errors.New("can't merge internal jsons")
}
baseBytes[len(baseBytes)-1] = ','
baseBytes = append(baseBytes, auxb[1:]...)
return baseBytes, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (b *Block) UnmarshalJSON(data []byte) error {
// As Base and auxb are at the same level in json,
// do unmarshalling separately for both structs.
auxb := new(auxBlockIn)
err := json.Unmarshal(data, auxb)
if err != nil {
return err
}
2021-03-01 13:44:47 +00:00
err = json.Unmarshal(data, &b.Header)
if err != nil {
return err
}
if len(auxb.Transactions) != 0 {
b.Transactions = make([]*transaction.Transaction, 0, len(auxb.Transactions))
for _, txBytes := range auxb.Transactions {
tx := &transaction.Transaction{}
err = tx.UnmarshalJSON(txBytes)
if err != nil {
return err
}
b.Transactions = append(b.Transactions, tx)
}
}
return nil
}
2021-03-15 10:00:04 +00:00
// GetExpectedBlockSize returns the expected block size which should be equal to io.GetVarSize(b).
2021-03-15 10:00:04 +00:00
func (b *Block) GetExpectedBlockSize() int {
var transactionsSize int
for _, tx := range b.Transactions {
transactionsSize += tx.Size()
}
return b.GetExpectedBlockSizeWithoutTransactions(len(b.Transactions)) + transactionsSize
}
// GetExpectedBlockSizeWithoutTransactions returns the expected block size without transactions size.
2021-03-15 10:00:04 +00:00
func (b *Block) GetExpectedBlockSizeWithoutTransactions(txCount int) int {
size := expectedHeaderSizeWithEmptyWitness - 1 - 1 + // 1 is for the zero-length (new(Header)).Script.Invocation/Verification
io.GetVarSize(&b.Script) +
io.GetVarSize(txCount)
if b.StateRootEnabled {
size += util.Uint256Size
}
return size
}
// ToStackItem converts Block to stackitem.Item.
func (b *Block) ToStackItem() stackitem.Item {
items := []stackitem.Item{
stackitem.NewByteArray(b.Hash().BytesBE()),
stackitem.NewBigInteger(big.NewInt(int64(b.Version))),
stackitem.NewByteArray(b.PrevHash.BytesBE()),
stackitem.NewByteArray(b.MerkleRoot.BytesBE()),
stackitem.NewBigInteger(big.NewInt(int64(b.Timestamp))),
stackitem.NewBigInteger(new(big.Int).SetUint64(b.Nonce)),
stackitem.NewBigInteger(big.NewInt(int64(b.Index))),
block: add PrimaryIndex to the stack item of block This is a bad one. $ ./bin/neo-go contract testinvokefunction -r https://rpc10.n3.nspcc.ru:10331 0xda65b600f7124ce6c79950c1772a36403104f2be getBlock 5762000 { "state": "HALT", "gasconsumed": "202812", "script": "AtDrVwARwB8MCGdldEJsb2NrDBS+8gQxQDYqd8FQmcfmTBL3ALZl2kFifVtS", "stack": [ { "type": "Array", "value": [ { "type": "ByteString", "value": "vq5IPTPEDRhz0JA4cQKIa6/o97pnJt/HfVkDRknd1rg=" }, { "type": "Integer", "value": "0" }, { "type": "ByteString", "value": "zFYF3LGaTKdbqVX99shaBUzTq9YjXb0jaPMjk2jdSP4=" }, { "type": "ByteString", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }, { "type": "Integer", "value": "1722060076994" }, { "type": "Integer", "value": "5293295626238767595" }, { "type": "Integer", "value": "5762000" }, { "type": "ByteString", "value": "LIt05Fpxhl/kXMX3EAGIASyOSQs=" }, { "type": "Integer", "value": "0" } ] } ], "exception": null, "notifications": [] } $ ./bin/neo-go contract testinvokefunction -r http://seed3.neo.org:10332 0xda65b600f7124ce6c79950c1772a36403104f2be getBlock 5762000 { "state": "HALT", "gasconsumed": "202812", "script": "AtDrVwARwB8MCGdldEJsb2NrDBS+8gQxQDYqd8FQmcfmTBL3ALZl2kFifVtS", "stack": [ { "type": "Array", "value": [ { "type": "ByteString", "value": "vq5IPTPEDRhz0JA4cQKIa6/o97pnJt/HfVkDRknd1rg=" }, { "type": "Integer", "value": "0" }, { "type": "ByteString", "value": "zFYF3LGaTKdbqVX99shaBUzTq9YjXb0jaPMjk2jdSP4=" }, { "type": "ByteString", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }, { "type": "Integer", "value": "1722060076994" }, { "type": "Integer", "value": "5293295626238767595" }, { "type": "Integer", "value": "5762000" }, { "type": "Integer", "value": "6" }, { "type": "ByteString", "value": "LIt05Fpxhl/kXMX3EAGIASyOSQs=" }, { "type": "Integer", "value": "0" } ] } ], "exception": null, "notifications": [] } 9 fields vs 10, notice the primary index right after the block number. Back when ac527650eb173bb1dbd799d44fea7309fce42ad3 initially added Ledger I've used https://github.com/neo-project/neo/pull/2215 as a reference and it was correct (no primary index). But then https://github.com/neo-project/neo/pull/2296 came into the C# codebase and while it looked like a pure refactoring it actually did add the primary index as well and this wasn't noticed. It wasn't noticed even when 3a4e0caeb8c019fcaaff50090286f5aef634d345 had touched some nearby code. In short, we had a completely wrong implementation of this call for more than three years. But looks like it's not a very popular one. Signed-off-by: Roman Khimov <roman@nspcc.ru>
2024-07-27 09:28:30 +00:00
stackitem.NewBigInteger(big.NewInt(int64(b.PrimaryIndex))),
stackitem.NewByteArray(b.NextConsensus.BytesBE()),
stackitem.NewBigInteger(big.NewInt(int64(len(b.Transactions)))),
}
if b.StateRootEnabled {
items = append(items, stackitem.NewByteArray(b.PrevStateRoot.BytesBE()))
}
return stackitem.NewArray(items)
}