github.com/MetalBlockchain/metalgo@v1.11.9/snow/consensus/snowman/snowmantest/block.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package snowmantest 5 6 import ( 7 "cmp" 8 "context" 9 "time" 10 11 "github.com/MetalBlockchain/metalgo/ids" 12 "github.com/MetalBlockchain/metalgo/snow/choices" 13 "github.com/MetalBlockchain/metalgo/utils" 14 ) 15 16 const ( 17 GenesisHeight uint64 = 0 18 GenesisUnixTimestamp int64 = 1 19 ) 20 21 var ( 22 _ utils.Sortable[*Block] = (*Block)(nil) 23 24 GenesisID = ids.GenerateTestID() 25 GenesisTimestamp = time.Unix(GenesisUnixTimestamp, 0) 26 GenesisBytes = GenesisID[:] 27 Genesis = BuildChain(1)[0] 28 ) 29 30 func BuildChild(parent *Block) *Block { 31 blkID := ids.GenerateTestID() 32 return &Block{ 33 TestDecidable: choices.TestDecidable{ 34 IDV: blkID, 35 StatusV: choices.Processing, 36 }, 37 ParentV: parent.ID(), 38 HeightV: parent.Height() + 1, 39 TimestampV: parent.Timestamp(), 40 BytesV: blkID[:], 41 } 42 } 43 44 func BuildChain(length int) []*Block { 45 if length == 0 { 46 return nil 47 } 48 49 genesis := &Block{ 50 TestDecidable: choices.TestDecidable{ 51 IDV: GenesisID, 52 StatusV: choices.Accepted, 53 }, 54 HeightV: GenesisHeight, 55 TimestampV: GenesisTimestamp, 56 BytesV: GenesisBytes, 57 } 58 return append([]*Block{genesis}, BuildDescendants(genesis, length-1)...) 59 } 60 61 func BuildDescendants(parent *Block, length int) []*Block { 62 chain := make([]*Block, length) 63 for i := range chain { 64 parent = BuildChild(parent) 65 chain[i] = parent 66 } 67 return chain 68 } 69 70 type Block struct { 71 choices.TestDecidable 72 73 ParentV ids.ID 74 HeightV uint64 75 TimestampV time.Time 76 VerifyV error 77 BytesV []byte 78 } 79 80 func (b *Block) Parent() ids.ID { 81 return b.ParentV 82 } 83 84 func (b *Block) Height() uint64 { 85 return b.HeightV 86 } 87 88 func (b *Block) Timestamp() time.Time { 89 return b.TimestampV 90 } 91 92 func (b *Block) Verify(context.Context) error { 93 return b.VerifyV 94 } 95 96 func (b *Block) Bytes() []byte { 97 return b.BytesV 98 } 99 100 func (b *Block) Compare(other *Block) int { 101 return cmp.Compare(b.HeightV, other.HeightV) 102 }