From 8105cd4112c9593089541f12e5f5008f3499a8bc Mon Sep 17 00:00:00 2001 From: noot Date: Fri, 11 Mar 2022 14:04:04 +0000 Subject: [PATCH] fix(dot/network): change BlockRequestMessage number from uint64 to uint32 --- dot/network/errors.go | 12 ++-- dot/network/helpers_test.go | 2 +- dot/network/message.go | 24 +++---- dot/network/message_test.go | 10 +-- dot/network/notifications.go | 4 +- dot/sync/chain_processor_test.go | 6 +- dot/sync/chain_sync.go | 16 ++--- dot/sync/chain_sync_test.go | 30 ++++----- dot/sync/message.go | 4 +- dot/sync/message_test.go | 24 +++---- lib/common/variadic/uint32OrHash.go | 85 ++++++++++++------------ lib/common/variadic/uint32OrHash_test.go | 66 +++++++----------- 12 files changed, 133 insertions(+), 150 deletions(-) diff --git a/dot/network/errors.go b/dot/network/errors.go index 44199f4249..17c1fd23d8 100644 --- a/dot/network/errors.go +++ b/dot/network/errors.go @@ -8,9 +8,11 @@ import ( ) var ( - errCannotValidateHandshake = errors.New("failed to validate handshake") - errMessageTypeNotValid = errors.New("message type is not valid") - errMessageIsNotHandshake = errors.New("failed to convert message to Handshake") - errInvalidHandshakeForPeer = errors.New("peer previously sent invalid handshake") - errHandshakeTimeout = errors.New("handshake timeout reached") + errCannotValidateHandshake = errors.New("failed to validate handshake") + errMessageTypeNotValid = errors.New("message type is not valid") + errMessageIsNotHandshake = errors.New("failed to convert message to Handshake") + errInvalidHandshakeForPeer = errors.New("peer previously sent invalid handshake") + errHandshakeTimeout = errors.New("handshake timeout reached") + errBlockRequestFromNumberInvalid = errors.New("block request message From number is not valid") + errInvalidStartingBlockType = errors.New("invalid StartingBlock in messsage") ) diff --git a/dot/network/helpers_test.go b/dot/network/helpers_test.go index 1632c9a1eb..378db3f4c3 100644 --- a/dot/network/helpers_test.go +++ b/dot/network/helpers_test.go @@ -111,7 +111,7 @@ func (s *testStreamHandler) readStream(stream libp2pnetwork.Stream, } } -var starting, _ = variadic.NewUint64OrHash(uint64(1)) +var starting, _ = variadic.NewUint32OrHash(uint32(1)) var one = uint32(1) diff --git a/dot/network/message.go b/dot/network/message.go index fe42657acd..798ed3157a 100644 --- a/dot/network/message.go +++ b/dot/network/message.go @@ -76,7 +76,7 @@ func (sd SyncDirection) String() string { // BlockRequestMessage is sent to request some blocks from a peer type BlockRequestMessage struct { RequestedData byte - StartingBlock variadic.Uint64OrHash // first byte 0 = block hash (32 byte), first byte 1 = block number (int64) + StartingBlock variadic.Uint32OrHash // first byte 0 = block hash (32 byte), first byte 1 = block number (uint32) EndBlockHash *common.Hash Direction SyncDirection // 0 = ascending, 1 = descending Max *uint32 @@ -133,14 +133,14 @@ func (bm *BlockRequestMessage) Encode() ([]byte, error) { msg.FromBlock = &pb.BlockRequest_Hash{ Hash: hash[:], } - } else if bm.StartingBlock.IsUint64() { - buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, bm.StartingBlock.Uint64()) + } else if bm.StartingBlock.IsUint32() { + buf := make([]byte, 4) + binary.LittleEndian.PutUint32(buf, bm.StartingBlock.Uint32()) msg.FromBlock = &pb.BlockRequest_Number{ Number: buf, } } else { - return nil, errors.New("invalid StartingBlock in messsage") + return nil, errInvalidStartingBlockType } return proto.Marshal(msg) @@ -155,21 +155,21 @@ func (bm *BlockRequestMessage) Decode(in []byte) error { } var ( - startingBlock *variadic.Uint64OrHash + startingBlock *variadic.Uint32OrHash endBlockHash *common.Hash max *uint32 ) switch from := msg.FromBlock.(type) { case *pb.BlockRequest_Hash: - startingBlock, err = variadic.NewUint64OrHash(common.BytesToHash(from.Hash)) + startingBlock, err = variadic.NewUint32OrHash(common.BytesToHash(from.Hash)) case *pb.BlockRequest_Number: - // TODO: we are receiving block requests w/ 4-byte From field; this should probably be - // 4-bytes as it represents a block number which is uint32 (#1854) - if len(from.Number) != 8 { - return errors.New("invalid BlockResponseMessage.From; uint64 is not 8 bytes") + if len(from.Number) != 4 { + return fmt.Errorf("%w expected 4 bytes, got %d bytes", errBlockRequestFromNumberInvalid, len(from.Number)) } - startingBlock, err = variadic.NewUint64OrHash(binary.LittleEndian.Uint64(from.Number)) + + number := binary.LittleEndian.Uint32(from.Number) + startingBlock, err = variadic.NewUint32OrHash(number) default: err = errors.New("invalid StartingBlock") } diff --git a/dot/network/message_test.go b/dot/network/message_test.go index a367ecb0e0..55746f6c54 100644 --- a/dot/network/message_test.go +++ b/dot/network/message_test.go @@ -25,7 +25,7 @@ func TestEncodeBlockRequestMessage(t *testing.T) { var one uint32 = 1 bm := &BlockRequestMessage{ RequestedData: 1, - StartingBlock: *variadic.NewUint64OrHashFromBytes(append([]byte{0}, genesisHash...)), + StartingBlock: *variadic.NewUint32OrHashFromBytes(append([]byte{0}, genesisHash...)), EndBlockHash: &endBlock, Direction: 1, Max: &one, @@ -51,7 +51,7 @@ func TestEncodeBlockRequestMessage_BlockHash(t *testing.T) { var one uint32 = 1 bm := &BlockRequestMessage{ RequestedData: 1, - StartingBlock: *variadic.NewUint64OrHashFromBytes(append([]byte{0}, genesisHash...)), + StartingBlock: *variadic.NewUint32OrHashFromBytes(append([]byte{0}, genesisHash...)), EndBlockHash: &endBlock, Direction: 1, Max: &one, @@ -74,7 +74,7 @@ func TestEncodeBlockRequestMessage_BlockNumber(t *testing.T) { var one uint32 = 1 bm := &BlockRequestMessage{ RequestedData: 1, - StartingBlock: *variadic.NewUint64OrHashFromBytes([]byte{1, 1}), + StartingBlock: *variadic.NewUint32OrHashFromBytes([]byte{1, 1}), EndBlockHash: &endBlock, Direction: 1, Max: &one, @@ -96,7 +96,7 @@ func TestBlockRequestString(t *testing.T) { bm := &BlockRequestMessage{ RequestedData: 1, - StartingBlock: *variadic.NewUint64OrHashFromBytes(append([]byte{0}, genesisHash...)), + StartingBlock: *variadic.NewUint32OrHashFromBytes(append([]byte{0}, genesisHash...)), EndBlockHash: nil, Direction: 1, Max: nil, @@ -116,7 +116,7 @@ func TestEncodeBlockRequestMessage_NoOptionals(t *testing.T) { bm := &BlockRequestMessage{ RequestedData: 1, - StartingBlock: *variadic.NewUint64OrHashFromBytes(append([]byte{0}, genesisHash...)), + StartingBlock: *variadic.NewUint32OrHashFromBytes(append([]byte{0}, genesisHash...)), EndBlockHash: nil, Direction: 1, Max: nil, diff --git a/dot/network/notifications.go b/dot/network/notifications.go index e05f164c44..55a278bbeb 100644 --- a/dot/network/notifications.go +++ b/dot/network/notifications.go @@ -253,7 +253,9 @@ func (s *Service) sendData(peer peer.ID, hs Handshake, info *notificationsProtoc return } - if s.host.messageCache != nil && s.host.messageCache.exists(peer, msg) { + _, isConsensusMsg := msg.(*ConsensusMessage) + + if s.host.messageCache != nil && s.host.messageCache.exists(peer, msg) && !isConsensusMsg { logger.Tracef("message has already been sent, ignoring: peer=%s msg=%s", peer, msg) return } diff --git a/dot/sync/chain_processor_test.go b/dot/sync/chain_processor_test.go index 5787392a76..9f3e1c80a6 100644 --- a/dot/sync/chain_processor_test.go +++ b/dot/sync/chain_processor_test.go @@ -37,7 +37,7 @@ func TestChainProcessor_HandleBlockResponse_ValidChain(t *testing.T) { // syncer makes request for chain startNum := 1 - start, err := variadic.NewUint64OrHash(startNum) + start, err := variadic.NewUint32OrHash(startNum) require.NoError(t, err) req := &network.BlockRequestMessage{ @@ -57,7 +57,7 @@ func TestChainProcessor_HandleBlockResponse_ValidChain(t *testing.T) { // syncer makes request for chain again (block 129+) startNum = 129 - start, err = variadic.NewUint64OrHash(startNum) + start, err = variadic.NewUint32OrHash(startNum) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -108,7 +108,7 @@ func TestChainProcessor_HandleBlockResponse_MissingBlocks(t *testing.T) { } startNum := 15 - start, err := variadic.NewUint64OrHash(startNum) + start, err := variadic.NewUint32OrHash(startNum) require.NoError(t, err) req := &network.BlockRequestMessage{ diff --git a/dot/sync/chain_sync.go b/dot/sync/chain_sync.go index 154c8f24fe..7a6e00828d 100644 --- a/dot/sync/chain_sync.go +++ b/dot/sync/chain_sync.go @@ -764,9 +764,9 @@ func (cs *chainSync) handleReadyBlock(bd *types.BlockData) { // determineSyncPeers returns a list of peers that likely have the blocks in the given block request. func (cs *chainSync) determineSyncPeers(req *network.BlockRequestMessage, peersTried map[peer.ID]struct{}) []peer.ID { - var start uint64 - if req.StartingBlock.IsUint64() { - start = req.StartingBlock.Uint64() + var start uint32 + if req.StartingBlock.IsUint32() { + start = req.StartingBlock.Uint32() } cs.RLock() @@ -796,7 +796,7 @@ func (cs *chainSync) determineSyncPeers(req *network.BlockRequestMessage, peersT // if peer definitely doesn't have any blocks we want in the request, // don't request from them - if start > 0 && uint64(state.number) < start { + if start > 0 && uint32(state.number) < start { continue } @@ -1005,18 +1005,18 @@ func workerToRequests(w *worker) ([]*network.BlockRequestMessage, error) { max = uint32(size) } - var start *variadic.Uint64OrHash + var start *variadic.Uint32OrHash if w.startHash.IsEmpty() { // worker startHash is unspecified if we are in bootstrap mode - start = variadic.MustNewUint64OrHash(uint64(startNumber)) + start = variadic.MustNewUint32OrHash(uint32(startNumber)) } else { // in tip-syncing mode, we know the hash of the block on the fork we wish to sync - start = variadic.MustNewUint64OrHash(w.startHash) + start = variadic.MustNewUint32OrHash(w.startHash) // if we're doing descending requests and not at the last (highest starting) request, // then use number as start block if w.direction == network.Descending && i != numRequests-1 { - start = variadic.MustNewUint64OrHash(startNumber) + start = variadic.MustNewUint32OrHash(startNumber) } } diff --git a/dot/sync/chain_sync_test.go b/dot/sync/chain_sync_test.go index 335863be65..07dca3337d 100644 --- a/dot/sync/chain_sync_test.go +++ b/dot/sync/chain_sync_test.go @@ -274,7 +274,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, @@ -291,14 +291,14 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, }, { RequestedData: network.RequestedDataHeader + network.RequestedDataBody + network.RequestedDataJustification, - StartingBlock: *variadic.MustNewUint64OrHash(1 + maxResponseSize), + StartingBlock: *variadic.MustNewUint32OrHash(1 + maxResponseSize), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, @@ -315,7 +315,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, @@ -332,7 +332,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(10), + StartingBlock: *variadic.MustNewUint32OrHash(10), EndBlockHash: nil, Direction: network.Descending, Max: &max9, @@ -349,14 +349,14 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, }, { RequestedData: network.RequestedDataHeader + network.RequestedDataBody + network.RequestedDataJustification, - StartingBlock: *variadic.MustNewUint64OrHash(1 + maxResponseSize), + StartingBlock: *variadic.MustNewUint32OrHash(1 + maxResponseSize), EndBlockHash: nil, Direction: network.Ascending, Max: &max128, @@ -374,7 +374,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: &(common.Hash{0xa}), Direction: network.Ascending, Max: &max128, @@ -393,7 +393,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(common.Hash{0xb}), + StartingBlock: *variadic.MustNewUint32OrHash(common.Hash{0xb}), EndBlockHash: &(common.Hash{0xc}), Direction: network.Ascending, Max: &max128, @@ -410,7 +410,7 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(10), + StartingBlock: *variadic.MustNewUint32OrHash(10), Direction: network.Ascending, Max: &max128, }, @@ -426,14 +426,14 @@ func TestWorkerToRequests(t *testing.T) { expected: []*network.BlockRequestMessage{ { RequestedData: network.RequestedDataHeader + network.RequestedDataBody + network.RequestedDataJustification, - StartingBlock: *variadic.MustNewUint64OrHash(1 + (maxResponseSize / 2)), + StartingBlock: *variadic.MustNewUint32OrHash(1 + (maxResponseSize / 2)), EndBlockHash: nil, Direction: network.Descending, Max: &max64, }, { RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1 + maxResponseSize + (maxResponseSize / 2)), + StartingBlock: *variadic.MustNewUint32OrHash(1 + maxResponseSize + (maxResponseSize / 2)), EndBlockHash: nil, Direction: network.Descending, Max: &max128, @@ -626,7 +626,7 @@ func TestChainSync_doSync(t *testing.T) { max := uint32(1) req := &network.BlockRequestMessage{ RequestedData: bootstrapRequestData, - StartingBlock: *variadic.MustNewUint64OrHash(1), + StartingBlock: *variadic.MustNewUint32OrHash(1), EndBlockHash: nil, Direction: network.Ascending, Max: &max, @@ -798,7 +798,7 @@ func TestChainSync_determineSyncPeers(t *testing.T) { require.Equal(t, 0, len(cs.ignorePeers)) // test peer's best block below number case, shouldn't include that peer - start, err := variadic.NewUint64OrHash(130) + start, err := variadic.NewUint32OrHash(130) require.NoError(t, err) req.StartingBlock = *start peers = cs.determineSyncPeers(req, peersTried) @@ -807,7 +807,7 @@ func TestChainSync_determineSyncPeers(t *testing.T) { // test peer tried case, should ignore peer already tried peersTried[testPeerA] = struct{}{} - req.StartingBlock = variadic.Uint64OrHash{} + req.StartingBlock = variadic.Uint32OrHash{} peers = cs.determineSyncPeers(req, peersTried) require.Equal(t, 1, len(peers)) require.Equal(t, []peer.ID{testPeerB}, peers) diff --git a/dot/sync/message.go b/dot/sync/message.go index e8169bfbda..cef2f42e25 100644 --- a/dot/sync/message.go +++ b/dot/sync/message.go @@ -42,7 +42,7 @@ func (s *Service) handleAscendingRequest(req *network.BlockRequestMessage) (*net } switch startBlock := req.StartingBlock.Value().(type) { - case uint64: + case uint32: if startBlock == 0 { startBlock = 1 } @@ -147,7 +147,7 @@ func (s *Service) handleDescendingRequest(req *network.BlockRequestMessage) (*ne } switch startBlock := req.StartingBlock.Value().(type) { - case uint64: + case uint32: bestBlockNumber, err := s.blockState.BestBlockNumber() if err != nil { return nil, fmt.Errorf("failed to get best block %d for request: %w", bestBlockNumber, err) diff --git a/dot/sync/message_test.go b/dot/sync/message_test.go index e4abcaa434..22b619d8aa 100644 --- a/dot/sync/message_test.go +++ b/dot/sync/message_test.go @@ -49,7 +49,7 @@ func TestService_CreateBlockResponse_MaxSize(t *testing.T) { addTestBlocksToState(t, maxResponseSize*2, s.blockState) // test ascending - start, err := variadic.NewUint64OrHash(uint64(1)) + start, err := variadic.NewUint32OrHash(1) require.NoError(t, err) req := &network.BlockRequestMessage{ @@ -97,7 +97,7 @@ func TestService_CreateBlockResponse_MaxSize(t *testing.T) { require.Equal(t, uint(16), resp.BlockData[15].Number()) // test descending - start, err = variadic.NewUint64OrHash(uint64(128)) + start, err = variadic.NewUint32OrHash(uint32(128)) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -115,7 +115,7 @@ func TestService_CreateBlockResponse_MaxSize(t *testing.T) { require.Equal(t, uint(1), resp.BlockData[127].Number()) max = uint32(maxResponseSize + 100) - start, err = variadic.NewUint64OrHash(uint64(256)) + start, err = variadic.NewUint32OrHash(uint32(256)) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -156,7 +156,7 @@ func TestService_CreateBlockResponse_StartHash(t *testing.T) { startHash, err := s.blockState.GetHashByNumber(1) require.NoError(t, err) - start, err := variadic.NewUint64OrHash(startHash) + start, err := variadic.NewUint32OrHash(startHash) require.NoError(t, err) req := &network.BlockRequestMessage{ @@ -195,7 +195,7 @@ func TestService_CreateBlockResponse_StartHash(t *testing.T) { startHash, err = s.blockState.GetHashByNumber(16) require.NoError(t, err) - start, err = variadic.NewUint64OrHash(startHash) + start, err = variadic.NewUint32OrHash(startHash) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -234,7 +234,7 @@ func TestService_CreateBlockResponse_StartHash(t *testing.T) { startHash, err = s.blockState.GetHashByNumber(256) require.NoError(t, err) - start, err = variadic.NewUint64OrHash(startHash) + start, err = variadic.NewUint32OrHash(startHash) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -254,7 +254,7 @@ func TestService_CreateBlockResponse_StartHash(t *testing.T) { startHash, err = s.blockState.GetHashByNumber(128) require.NoError(t, err) - start, err = variadic.NewUint64OrHash(startHash) + start, err = variadic.NewUint32OrHash(startHash) require.NoError(t, err) req = &network.BlockRequestMessage{ @@ -278,7 +278,7 @@ func TestService_CreateBlockResponse_Ascending_EndHash(t *testing.T) { addTestBlocksToState(t, uint(maxResponseSize+1), s.blockState) // should error if end < start - start, err := variadic.NewUint64OrHash(uint64(128)) + start, err := variadic.NewUint32OrHash(uint32(128)) require.NoError(t, err) end, err := s.blockState.GetHashByNumber(1) @@ -296,7 +296,7 @@ func TestService_CreateBlockResponse_Ascending_EndHash(t *testing.T) { require.Error(t, err) // base case - start, err = variadic.NewUint64OrHash(uint64(1)) + start, err = variadic.NewUint32OrHash(uint32(1)) require.NoError(t, err) end, err = s.blockState.GetHashByNumber(128) @@ -322,7 +322,7 @@ func TestService_CreateBlockResponse_Descending_EndHash(t *testing.T) { addTestBlocksToState(t, uint(maxResponseSize+1), s.blockState) // should error if start < end - start, err := variadic.NewUint64OrHash(uint64(1)) + start, err := variadic.NewUint32OrHash(uint32(1)) require.NoError(t, err) end, err := s.blockState.GetHashByNumber(128) @@ -340,7 +340,7 @@ func TestService_CreateBlockResponse_Descending_EndHash(t *testing.T) { require.Error(t, err) // base case - start, err = variadic.NewUint64OrHash(uint64(128)) + start, err = variadic.NewUint32OrHash(uint32(128)) require.NoError(t, err) end, err = s.blockState.GetHashByNumber(1) @@ -476,7 +476,7 @@ func TestService_CreateBlockResponse_Fields(t *testing.T) { } endHash := s.blockState.BestBlockHash() - start, err := variadic.NewUint64OrHash(uint64(1)) + start, err := variadic.NewUint32OrHash(uint32(1)) require.NoError(t, err) err = s.blockState.CompareAndSetBlockData(bds) diff --git a/lib/common/variadic/uint32OrHash.go b/lib/common/variadic/uint32OrHash.go index 2e45a731bc..6bf597505c 100644 --- a/lib/common/variadic/uint32OrHash.go +++ b/lib/common/variadic/uint32OrHash.go @@ -11,35 +11,35 @@ import ( "github.com/ChainSafe/gossamer/lib/common" ) -// Uint64OrHash represents an optional interface type (int,hash). -type Uint64OrHash struct { +// Uint32OrHash represents a variadic type that is either uint32 or common.Hash. +type Uint32OrHash struct { value interface{} } -// NewUint64OrHash returns a new variadic.Uint64OrHash given an int, uint64, or Hash -func NewUint64OrHash(value interface{}) (*Uint64OrHash, error) { +// NewUint32OrHash returns a new variadic.Uint32OrHash given an int, uint32, or Hash +func NewUint32OrHash(value interface{}) (*Uint32OrHash, error) { switch v := value.(type) { - case int: - return &Uint64OrHash{ - value: uint64(v), + case int: // in order to accept constants int such as `NewUint32OrHash(1)` + return &Uint32OrHash{ + value: uint32(v), }, nil - case uint64: - return &Uint64OrHash{ + case uint32: + return &Uint32OrHash{ value: v, }, nil case common.Hash: - return &Uint64OrHash{ + return &Uint32OrHash{ value: v, }, nil default: - return nil, errors.New("value is not uint64 or common.Hash") + return nil, errors.New("value is not uint32 or common.Hash") } } -// MustNewUint64OrHash returns a new variadic.Uint64OrHash given an int, uint64, or Hash +// MustNewUint32OrHash returns a new variadic.Uint32OrHash given an int, uint32, or Hash // It panics if the input value is invalid -func MustNewUint64OrHash(value interface{}) *Uint64OrHash { - val, err := NewUint64OrHash(value) +func MustNewUint32OrHash(value interface{}) *Uint32OrHash { + val, err := NewUint32OrHash(value) if err != nil { panic(err) } @@ -47,20 +47,20 @@ func MustNewUint64OrHash(value interface{}) *Uint64OrHash { return val } -// NewUint64OrHashFromBytes returns a new variadic.Uint64OrHash from an encoded variadic uint64 or hash -func NewUint64OrHashFromBytes(data []byte) *Uint64OrHash { +// NewUint32OrHashFromBytes returns a new variadic.Uint32OrHash from an encoded variadic uint32 or hash +func NewUint32OrHashFromBytes(data []byte) *Uint32OrHash { firstByte := data[0] if firstByte == 0 { - return &Uint64OrHash{ + return &Uint32OrHash{ value: common.NewHash(data[1:]), } } else if firstByte == 1 { num := data[1:] - if len(num) < 8 { - num = common.AppendZeroes(num, 8) + if len(num) < 4 { + num = common.AppendZeroes(num, 4) } - return &Uint64OrHash{ - value: binary.LittleEndian.Uint64(num), + return &Uint32OrHash{ + value: binary.LittleEndian.Uint32(num), } } else { return nil @@ -68,7 +68,7 @@ func NewUint64OrHashFromBytes(data []byte) *Uint64OrHash { } // Value returns the interface value. -func (x *Uint64OrHash) Value() interface{} { +func (x *Uint32OrHash) Value() interface{} { if x == nil { return nil } @@ -76,7 +76,7 @@ func (x *Uint64OrHash) Value() interface{} { } // IsHash returns true if the value is a hash -func (x *Uint64OrHash) IsHash() bool { +func (x *Uint32OrHash) IsHash() bool { if x == nil { return false } @@ -84,8 +84,8 @@ func (x *Uint64OrHash) IsHash() bool { return is } -// Hash returns the value as a common.Hash. it panics if the value is not a hash. -func (x *Uint64OrHash) Hash() common.Hash { +// Hash returns the value as a common.Hash. It panics if the value is not a hash. +func (x *Uint32OrHash) Hash() common.Hash { if !x.IsHash() { panic("value is not common.Hash") } @@ -93,32 +93,31 @@ func (x *Uint64OrHash) Hash() common.Hash { return x.value.(common.Hash) } -// IsUint64 returns true if the value is a hash -func (x *Uint64OrHash) IsUint64() bool { +// IsUint32 returns true if the value is a uint32 +func (x *Uint32OrHash) IsUint32() bool { if x == nil { return false } - _, is := x.value.(uint64) + _, is := x.value.(uint32) return is } -// Uint64 returns the value as a uint64. it panics if the value is not a hash. -func (x *Uint64OrHash) Uint64() uint64 { - if !x.IsUint64() { - panic("value is not uint64") +// Uint32 returns the value as a uint32. It panics if the value is not a uint32. +func (x *Uint32OrHash) Uint32() uint32 { + if !x.IsUint32() { + panic("value is not uint32") } - return x.value.(uint64) + return x.value.(uint32) } -// Encode will encode a uint64 or hash into the SCALE spec -func (x *Uint64OrHash) Encode() ([]byte, error) { +// Encode will encode a Uint32OrHash using SCALE +func (x *Uint32OrHash) Encode() ([]byte, error) { var encMsg []byte switch c := x.Value().(type) { - case uint64: - startingBlockByteArray := make([]byte, 8) - binary.LittleEndian.PutUint64(startingBlockByteArray, c) - + case uint32: + startingBlockByteArray := make([]byte, 4) + binary.LittleEndian.PutUint32(startingBlockByteArray, c) encMsg = append(encMsg, append([]byte{1}, startingBlockByteArray...)...) case common.Hash: encMsg = append(encMsg, append([]byte{0}, c.ToBytes()...)...) @@ -126,8 +125,8 @@ func (x *Uint64OrHash) Encode() ([]byte, error) { return encMsg, nil } -// Decode will decode the Uint64OrHash into a hash or uint64 -func (x *Uint64OrHash) Decode(r io.Reader) error { +// Decode decodes a value into a Uint32OrHash +func (x *Uint32OrHash) Decode(r io.Reader) error { startingBlockType, err := common.ReadByte(r) if err != nil { return err @@ -140,12 +139,12 @@ func (x *Uint64OrHash) Decode(r io.Reader) error { } x.value = common.NewHash(hash) } else { - num := make([]byte, 8) + num := make([]byte, 4) _, err = r.Read(num) if err != nil { return err } - x.value = binary.LittleEndian.Uint64(num) + x.value = binary.LittleEndian.Uint32(num) } return nil } diff --git a/lib/common/variadic/uint32OrHash_test.go b/lib/common/variadic/uint32OrHash_test.go index 72e861a05b..65f27880a9 100644 --- a/lib/common/variadic/uint32OrHash_test.go +++ b/lib/common/variadic/uint32OrHash_test.go @@ -11,50 +11,31 @@ import ( "github.com/stretchr/testify/require" ) -func TestNewUint64OrHash(t *testing.T) { +func TestNewUint32OrHash(t *testing.T) { hash, err := common.HexToHash("0xdcd1346701ca8396496e52aa2785b1748deb6db09551b72159dcb3e08991025b") - if err != nil { - t.Fatal(err) - } - - res, err := NewUint64OrHash(hash) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) - if resValue, ok := res.Value().(common.Hash); !ok || resValue != hash { - t.Fatalf("Fail: got %x expected %x", resValue, hash) - } + res, err := NewUint32OrHash(hash) + require.NoError(t, err) + require.Equal(t, res.Value(), hash) num := 77 - res, err = NewUint64OrHash(num) - if err != nil { - t.Fatal(err) - } - - if resValue, ok := res.Value().(uint64); !ok || resValue != uint64(num) { - t.Fatalf("Fail: got %d expected %d", resValue, num) - } + res, err = NewUint32OrHash(num) + require.NoError(t, err) + require.Equal(t, uint32(num), res.Value()) - res, err = NewUint64OrHash(uint64(num)) - if err != nil { - t.Fatal(err) - } - - if resValue, ok := res.Value().(uint64); !ok || resValue != uint64(num) { - t.Fatalf("Fail: got %d expected %d", resValue, uint64(num)) - } + res, err = NewUint32OrHash(uint32(num)) + require.NoError(t, err) + require.Equal(t, uint32(num), res.Value()) } -func TestNewUint64OrHashFromBytes(t *testing.T) { +func TestNewUint32OrHashFromBytes(t *testing.T) { genesisHash, err := common.HexToBytes("0xdcd1346701ca8396496e52aa2785b1748deb6db09551b72159dcb3e08991025b") - if err != nil || genesisHash == nil { - t.Fatal(err) - } + require.NoError(t, err) - buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, uint64(1)) + buf := make([]byte, 4) + binary.LittleEndian.PutUint32(buf, uint32(1)) for _, x := range []struct { description string @@ -72,24 +53,23 @@ func TestNewUint64OrHashFromBytes(t *testing.T) { description: "block request with Block Number int type 1", targetHash: buf, targetFirstByte: 1, - expectedType: (uint64)(0), + expectedType: (uint32)(0), }, } { t.Run(x.description, func(t *testing.T) { data := append([]byte{x.targetFirstByte}, x.targetHash...) - uint64OrHash := NewUint64OrHashFromBytes(data) + val := NewUint32OrHashFromBytes(data) require.NoError(t, err) - require.NotNil(t, uint64OrHash) - require.IsType(t, x.expectedType, uint64OrHash.Value()) - if x.expectedType == (uint64)(0) { - startingBlockByteArray := make([]byte, 8) - binary.LittleEndian.PutUint64(startingBlockByteArray, uint64OrHash.Value().(uint64)) + require.IsType(t, x.expectedType, val.Value()) + + if x.expectedType == (uint32)(0) { + startingBlockByteArray := make([]byte, 4) + binary.LittleEndian.PutUint32(startingBlockByteArray, val.Value().(uint32)) require.Equal(t, x.targetHash, startingBlockByteArray) } else { - require.Equal(t, common.NewHash(x.targetHash), uint64OrHash.Value()) + require.Equal(t, common.NewHash(x.targetHash), val.Value()) } }) } - }