github.com/koko1123/flow-go-1@v0.29.6/state/protocol/inmem/encodable_test.go (about)

     1  package inmem_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/koko1123/flow-go-1/model/encodable"
    11  	"github.com/koko1123/flow-go-1/model/flow"
    12  	"github.com/koko1123/flow-go-1/state/protocol/inmem"
    13  	"github.com/koko1123/flow-go-1/utils/unittest"
    14  )
    15  
    16  // test that we have the same snapshot after an encode/decode cycle
    17  // in particular with differing public key implementations
    18  func TestEncodeDecode(t *testing.T) {
    19  
    20  	participants := unittest.IdentityListFixture(10, unittest.WithAllRoles())
    21  	// add a partner, which has its key represented as an encodable wrapper
    22  	// type rather than the direct crypto type
    23  	partner := unittest.IdentityFixture(unittest.WithKeys, func(identity *flow.Identity) {
    24  		identity.NetworkPubKey = encodable.NetworkPubKey{PublicKey: identity.NetworkPubKey}
    25  	})
    26  	participants = append(participants, partner)
    27  	initialSnapshot := unittest.RootSnapshotFixture(participants)
    28  
    29  	// encode then decode the snapshot
    30  	var decodedSnapshot inmem.EncodableSnapshot
    31  	bz, err := json.Marshal(initialSnapshot.Encodable())
    32  	require.NoError(t, err)
    33  	err = json.Unmarshal(bz, &decodedSnapshot)
    34  	require.NoError(t, err)
    35  
    36  	// check that the computed and stored result IDs are consistent
    37  	decodedResult, decodedSeal := decodedSnapshot.LatestResult, decodedSnapshot.LatestSeal
    38  	assert.Equal(t, decodedResult.ID(), decodedSeal.ResultID)
    39  }
    40  
    41  // TestStrippedEncodeDecode tests that the protocol state snapshot can be encoded to JSON skipping the network address
    42  // and decoded back successfully
    43  func TestStrippedEncodeDecode(t *testing.T) {
    44  	participants := unittest.IdentityListFixture(10, unittest.WithAllRoles())
    45  	initialSnapshot := unittest.RootSnapshotFixture(participants)
    46  
    47  	// encode the snapshot
    48  	strippedSnapshot := inmem.StrippedInmemSnapshot(initialSnapshot.Encodable())
    49  	snapshotJson, err := json.Marshal(strippedSnapshot)
    50  	require.NoError(t, err)
    51  	// check that the json string does not contain "Address"
    52  	require.NotContains(t, snapshotJson, "Address")
    53  
    54  	// decode the snapshots
    55  	var decodedSnapshot inmem.EncodableSnapshot
    56  	err = json.Unmarshal(snapshotJson, &decodedSnapshot)
    57  	require.NoError(t, err)
    58  	// check that the network addresses for all the identities are still empty
    59  	assert.Len(t, decodedSnapshot.Identities.Filter(func(id *flow.Identity) bool {
    60  		return id.Address == ""
    61  	}), len(participants))
    62  }