diff --git a/dapps/faucet/dapp.go b/dapps/faucet/dapp.go index 2c930afc9dd428cd0fd6f0124a9f6a0d47642da0..0bc74cb23579dabf7fbe58bafad8788d6692f069 100644 --- a/dapps/faucet/dapp.go +++ b/dapps/faucet/dapp.go @@ -107,7 +107,7 @@ func configure(*node.Plugin) { log.Warnf("couldn't fulfill funding request to %s: %s", addr, err) return } - log.Infof("sent funds to address %s via tx %s and msg %s", addr, txID, msg.Id().String()) + log.Infof("sent funds to address %s via tx %s and msg %s", addr, txID, msg.ID().String()) }, workerpool.WorkerCount(fundingWorkerCount), workerpool.QueueSize(fundingWorkerQueueSize)) configureEvents() diff --git a/dapps/faucet/packages/faucet_test.go b/dapps/faucet/packages/faucet_test.go index f321c74035f2e85a006312f0007f432cc8745397..2e5853b8c536808afd7559c607c9a8089d64610f 100644 --- a/dapps/faucet/packages/faucet_test.go +++ b/dapps/faucet/packages/faucet_test.go @@ -26,8 +26,8 @@ func TestIsFaucetReq(t *testing.T) { return } faucetMsg := message.New( - message.EmptyId, - message.EmptyId, + message.EmptyID, + message.EmptyID, time.Now(), local.PublicKey(), 0, @@ -37,8 +37,8 @@ func TestIsFaucetReq(t *testing.T) { ) dataMsg := message.New( - message.EmptyId, - message.EmptyId, + message.EmptyID, + message.EmptyID, time.Now(), local.PublicKey(), 0, diff --git a/dapps/faucet/packages/payload/payload.go b/dapps/faucet/packages/payload/payload.go index ba5474352b902c7c1cc3205aacdbe3728a216729..6e6e0a9659008a420acdfd077f04447a3c0c9a61 100644 --- a/dapps/faucet/packages/payload/payload.go +++ b/dapps/faucet/packages/payload/payload.go @@ -4,6 +4,7 @@ import ( "context" "crypto" + // Only want to use init _ "golang.org/x/crypto/blake2b" "github.com/iotaledger/goshimmer/packages/binary/messagelayer/message" @@ -54,7 +55,7 @@ func init() { // FromBytes parses the marshaled version of a Payload into an object. // It either returns a new Payload or fills an optionally provided Payload with the parsed information. -func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, err error, consumedBytes int) { +func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, consumedBytes int, err error) { // determine the target object that will hold the unmarshaled information switch len(optionalTargetObject) { case 0: @@ -123,7 +124,7 @@ func (faucetPayload *Payload) Bytes() []byte { // Unmarshal unmarshals a given slice of bytes and fills the object. func (faucetPayload *Payload) Unmarshal(data []byte) (err error) { - _, err, _ = FromBytes(data, faucetPayload) + _, _, err = FromBytes(data, faucetPayload) return } diff --git a/dapps/faucet/packages/payload/payload_test.go b/dapps/faucet/packages/payload/payload_test.go index fe9d3b8693acd62fd4885698560a5c6486ce8476..7bf0a0b6891ef1efd7cc1ece384bf0af0f334b99 100644 --- a/dapps/faucet/packages/payload/payload_test.go +++ b/dapps/faucet/packages/payload/payload_test.go @@ -25,8 +25,8 @@ func ExamplePayload() { // 2. build actual message tx := message.New( - message.EmptyId, - message.EmptyId, + message.EmptyID, + message.EmptyID, time.Now(), local.PublicKey(), 0, @@ -43,14 +43,14 @@ func TestPayload(t *testing.T) { panic(err) } - clonedPayload1, err, _ := FromBytes(originalPayload.Bytes()) + clonedPayload1, _, err := FromBytes(originalPayload.Bytes()) if err != nil { panic(err) } assert.Equal(t, originalPayload.Address(), clonedPayload1.Address()) - clonedPayload2, err, _ := FromBytes(clonedPayload1.Bytes()) + clonedPayload2, _, err := FromBytes(clonedPayload1.Bytes()) if err != nil { panic(err) } diff --git a/dapps/networkdelay/webapi.go b/dapps/networkdelay/webapi.go index 53f72ea6f2da3336e2bc5f3153ab95fff80fbab0..dbb29ef3e064259f8e4ab590aa948bf7fea9b355 100644 --- a/dapps/networkdelay/webapi.go +++ b/dapps/networkdelay/webapi.go @@ -28,7 +28,7 @@ func broadcastNetworkDelayObject(c echo.Context) error { if err != nil { return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } - return c.JSON(http.StatusOK, Response{ID: msg.Id().String()}) + return c.JSON(http.StatusOK, Response{ID: msg.ID().String()}) } // Response contains the ID of the message sent. diff --git a/dapps/valuetransfers/packages/payload/payload_test.go b/dapps/valuetransfers/packages/payload/payload_test.go index 743e7310a0c3612e7f212df0834bdc5979230297..ae88b36ff483864bdff271a01b9454e41e631651 100644 --- a/dapps/valuetransfers/packages/payload/payload_test.go +++ b/dapps/valuetransfers/packages/payload/payload_test.go @@ -47,10 +47,10 @@ func ExamplePayload() { // 3. build actual transaction (the base layer creates this and wraps the ontology provided payload) tx := message.New( // trunk in "network tangle" ontology (filled by tipSelector) - message.EmptyId, + message.EmptyID, // branch in "network tangle" ontology (filled by tipSelector) - message.EmptyId, + message.EmptyID, // the time when the transaction was created time.Now(), diff --git a/dapps/valuetransfers/packages/tangle/signature_filter_test.go b/dapps/valuetransfers/packages/tangle/signature_filter_test.go index 2ac1a596ed3bcc96dd5cd1afaacdf426fa7f705f..cf47cbc11045abdbeec4f14ada2efaae6ddd62c2 100644 --- a/dapps/valuetransfers/packages/tangle/signature_filter_test.go +++ b/dapps/valuetransfers/packages/tangle/signature_filter_test.go @@ -91,7 +91,7 @@ func TestSignatureFilter(t *testing.T) { marshalUtil.WriteUint32(valuePayload.Type) // parse modified bytes back into a payload object - dataPayload, err, _ := messagePayload.DataFromBytes(marshalUtil.Bytes()) + dataPayload, _, err := messagePayload.DataFromBytes(marshalUtil.Bytes()) require.NoError(t, err) // parse message bytes diff --git a/dapps/valuetransfers/packages/transaction/id.go b/dapps/valuetransfers/packages/transaction/id.go index f1acc5e7ef17d5d5702d6472b3dcae0877e2aac8..dbbd4e4f073f4a8ea16166d9a54d32f3d9dfe4c0 100644 --- a/dapps/valuetransfers/packages/transaction/id.go +++ b/dapps/valuetransfers/packages/transaction/id.go @@ -82,6 +82,7 @@ func (id ID) String() string { return base58.Encode(id[:]) } +// GenesisID represents the genesis ID. var GenesisID ID // IDLength contains the amount of bytes that a marshaled version of the ID contains. diff --git a/go.mod b/go.mod index 45c1d91027222e903722017233cc0f7897afc245..163c7a7dde778f0a882e1c53aae98da23c60486f 100644 --- a/go.mod +++ b/go.mod @@ -35,5 +35,6 @@ require ( golang.org/x/tools v0.0.0-20200330040139-fa3cc9eebcfe // indirect google.golang.org/grpc v1.30.0 google.golang.org/grpc/examples v0.0.0-20200617041141-9a465503579e // indirect + google.golang.org/protobuf v1.25.0 gopkg.in/src-d/go-git.v4 v4.13.1 ) diff --git a/go.sum b/go.sum index c425a1354e572c4cda338bfb4c8d02f538b1fa50..ba8ea031e2a8b059520212ed4b52025ace2b677d 100644 --- a/go.sum +++ b/go.sum @@ -175,6 +175,7 @@ github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:x github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= @@ -186,6 +187,7 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= @@ -667,6 +669,8 @@ google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c/go.mod h1:IbNlFCBr google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20200406120821-33397c535dc2 h1:KlOjjpQjL4dqscfbhtQvAnRMm5PaRTchHHczffkUiq0= google.golang.org/genproto v0.0.0-20200406120821-33397c535dc2/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -685,8 +689,12 @@ google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/packages/binary/datastructure/queue/queue.go b/packages/binary/datastructure/queue/queue.go index 33cd34f9344607d86596e422cb7c8d539b4a5c66..d0e87125fa8bfdf02377773ebd75be41027c870c 100644 --- a/packages/binary/datastructure/queue/queue.go +++ b/packages/binary/datastructure/queue/queue.go @@ -4,6 +4,7 @@ import ( "sync" ) +// Queue represents a ring buffer. type Queue struct { ringBuffer []interface{} read int @@ -13,6 +14,7 @@ type Queue struct { mutex sync.Mutex } +// New creates a new queue with the specified capacity. func New(capacity int) *Queue { return &Queue{ ringBuffer: make([]interface{}, capacity), @@ -20,6 +22,7 @@ func New(capacity int) *Queue { } } +// Size returns the size of the queue. func (queue *Queue) Size() int { queue.mutex.Lock() defer queue.mutex.Unlock() @@ -27,6 +30,7 @@ func (queue *Queue) Size() int { return queue.size } +// Capacity returns the capacity of the queue. func (queue *Queue) Capacity() int { queue.mutex.Lock() defer queue.mutex.Unlock() @@ -34,6 +38,8 @@ func (queue *Queue) Capacity() int { return queue.capacity } +// Offer adds an element ot the queue and returns true. +// If the buffer is full, it drops it and returns false. func (queue *Queue) Offer(element interface{}) bool { queue.mutex.Lock() defer queue.mutex.Unlock() @@ -49,6 +55,8 @@ func (queue *Queue) Offer(element interface{}) bool { return true } +// Poll returns and removes the oldest element in the queue and true if successful. +// If returns false is the queue is empty. func (queue *Queue) Poll() (element interface{}, success bool) { queue.mutex.Lock() defer queue.mutex.Unlock() diff --git a/packages/binary/datastructure/queue/queue_test.go b/packages/binary/datastructure/queue/queue_test.go index 67d5351b2683004d13108403c2f0aafcf4c094ed..5a39242be2dafd56203d5b82e2cad48ac7f26cd5 100644 --- a/packages/binary/datastructure/queue/queue_test.go +++ b/packages/binary/datastructure/queue/queue_test.go @@ -74,7 +74,7 @@ func TestQueueOfferConcurrencySafe(t *testing.T) { for i := 0; i < 100; i++ { value, ok := queue.Poll() assert.True(t, ok) - counter[value.(int)] += 1 + counter[value.(int)]++ } assert.Equal(t, 0, queue.Size()) diff --git a/packages/binary/datastructure/random_map.go b/packages/binary/datastructure/random_map.go index ff1692c441440377d9dc325d1745401e738d7f3d..0b55ed0ce903bf2c5beb65c4c5360da9ae1bcb48 100644 --- a/packages/binary/datastructure/random_map.go +++ b/packages/binary/datastructure/random_map.go @@ -16,6 +16,7 @@ type randomMapEntry struct { keyIndex int } +// RandomMap defines a map with extended ability to return a random entry. type RandomMap struct { rawMap map[interface{}]*randomMapEntry keys []interface{} @@ -23,6 +24,7 @@ type RandomMap struct { mutex sync.RWMutex } +// NewRandomMap creates a new random map func NewRandomMap() *RandomMap { return &RandomMap{ rawMap: make(map[interface{}]*randomMapEntry), @@ -30,6 +32,8 @@ func NewRandomMap() *RandomMap { } } +// Set associates the specified value with the specified key. +// If the association already exists, it updates the value. func (rmap *RandomMap) Set(key interface{}, value interface{}) (updated bool) { rmap.mutex.Lock() @@ -58,6 +62,7 @@ func (rmap *RandomMap) Set(key interface{}, value interface{}) (updated bool) { return } +// Get returns the value to which the specified key is mapped. func (rmap *RandomMap) Get(key interface{}) (result interface{}, exists bool) { rmap.mutex.RLock() @@ -71,6 +76,7 @@ func (rmap *RandomMap) Get(key interface{}) (result interface{}, exists bool) { return } +// Delete removes the mapping for the specified key in the map. func (rmap *RandomMap) Delete(key interface{}) (result interface{}, exists bool) { rmap.mutex.RLock() @@ -106,6 +112,7 @@ func (rmap *RandomMap) Delete(key interface{}) (result interface{}, exists bool) return } +// Size returns the number of of key-value mappings in the map. func (rmap *RandomMap) Size() (result int) { rmap.mutex.RLock() @@ -116,6 +123,7 @@ func (rmap *RandomMap) Size() (result int) { return } +// RandomEntry returns a random value from the map. func (rmap *RandomMap) RandomEntry() (result interface{}) { rmap.mutex.RLock() diff --git a/packages/binary/drng/dispatcher.go b/packages/binary/drng/dispatcher.go index 4e79a85a2a1d229be302c6c8352b676a095792dd..93cb7ddeb5dcbca3e22e22ef34a45980a15290ea 100644 --- a/packages/binary/drng/dispatcher.go +++ b/packages/binary/drng/dispatcher.go @@ -6,9 +6,9 @@ import ( "github.com/iotaledger/goshimmer/packages/binary/drng/payload" "github.com/iotaledger/goshimmer/packages/binary/drng/payload/header" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events" - cb "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/events" + cb "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/hive.go/marshalutil" ) @@ -36,7 +36,7 @@ func (drng *DRNG) Dispatch(issuer ed25519.PublicKey, timestamp time.Time, payloa drng.Events.CollectiveBeacon.Trigger(cbEvent) // process collectiveBeacon - if err := collectiveBeacon.ProcessBeacon(drng.State, cbEvent); err != nil { + if err := collectivebeacon.ProcessBeacon(drng.State, cbEvent); err != nil { return err } diff --git a/packages/binary/drng/dispatcher_test.go b/packages/binary/drng/dispatcher_test.go index bef89e1c38367216081d971603eae6a7bbf85c4d..dc54b49268666d24a84e2d747c1c34a2c90e1d88 100644 --- a/packages/binary/drng/dispatcher_test.go +++ b/packages/binary/drng/dispatcher_test.go @@ -8,8 +8,8 @@ import ( "github.com/iotaledger/goshimmer/packages/binary/drng/payload" "github.com/iotaledger/goshimmer/packages/binary/drng/payload/header" "github.com/iotaledger/goshimmer/packages/binary/drng/state" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon" - cbPayload "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon" + cbPayload "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/hive.go/marshalutil" "github.com/stretchr/testify/require" @@ -31,7 +31,7 @@ func init() { dpkTest, _ = hex.DecodeString("80b319dbf164d852cdac3d86f0b362e0131ddeae3d87f6c3c5e3b6a9de384093b983db88f70e2008b0e945657d5980e2") timestampTest = time.Now() - rand, _ := collectiveBeacon.ExtractRandomness(signatureTest) + rand, _ := collectivebeacon.ExtractRandomness(signatureTest) randomnessTest = &state.Randomness{ Round: 1, Randomness: rand, diff --git a/packages/binary/drng/drng.go b/packages/binary/drng/drng.go index 15f6eadad97bcb5c31c54556b846f9bb0997c12c..357457b93ffa898f5de114f911871c75fdef8ecc 100644 --- a/packages/binary/drng/drng.go +++ b/packages/binary/drng/drng.go @@ -2,7 +2,7 @@ package drng import ( "github.com/iotaledger/goshimmer/packages/binary/drng/state" - cbEvents "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events" + cbEvents "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/events" "github.com/iotaledger/hive.go/events" ) diff --git a/packages/binary/drng/payload/payload.go b/packages/binary/drng/payload/payload.go index fe9768f70983397509e321fc211a9fd6af708891..8d49709b4789773b376f5544d69b81c9cf7309c0 100644 --- a/packages/binary/drng/payload/payload.go +++ b/packages/binary/drng/payload/payload.go @@ -33,11 +33,11 @@ func New(header header.Header, data []byte) *Payload { // Parse is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package. func Parse(marshalUtil *marshalutil.MarshalUtil) (*Payload, error) { - if payload, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return FromBytes(data) }); err != nil { + payload, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return FromBytes(data) }) + if err != nil { return &Payload{}, err - } else { - return payload.(*Payload), nil } + return payload.(*Payload), nil } // FromBytes parses the marshaled version of a Payload into an object. @@ -85,6 +85,7 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, return } +// Bytes returns the drng payload bytes. func (payload *Payload) Bytes() (bytes []byte) { // acquire lock for reading bytes payload.bytesMutex.RLock() @@ -128,16 +129,20 @@ func (payload *Payload) String() string { // region Payload implementation /////////////////////////////////////////////////////////////////////////////////////// +// Type defines the type of the drng payload. var Type = payload.Type(111) +// Type returns the type of the drng payload. func (payload *Payload) Type() payload.Type { return Type } +// Marshal marshals the drng payload into bytes. func (payload *Payload) Marshal() (bytes []byte, err error) { return payload.Bytes(), nil } +// Unmarshal unmarshals the given bytes into a drng payload. func (payload *Payload) Unmarshal(data []byte) (err error) { _, _, err = FromBytes(data, payload) diff --git a/packages/binary/drng/state/state.go b/packages/binary/drng/state/state.go index 95e45d37be3c34f2d252ab177ae62f0ee8fbecf3..27e46e6577202bc34f6598d97e66eb0f6f58b83c 100644 --- a/packages/binary/drng/state/state.go +++ b/packages/binary/drng/state/state.go @@ -35,7 +35,7 @@ type Committee struct { DistributedPK []byte } -// The state of the DRNG. +// State represents the state of the DRNG. type State struct { randomness *Randomness committee *Committee @@ -73,7 +73,7 @@ func (s *State) Randomness() Randomness { return *s.randomness } -// Update committee updates the committee of the DRNG state +// UpdateCommittee updates the committee of the DRNG state func (s *State) UpdateCommittee(c *Committee) { s.mutex.Lock() defer s.mutex.Unlock() diff --git a/packages/binary/drng/subtypes/collectiveBeacon/payload/common.go b/packages/binary/drng/subtypes/collectiveBeacon/payload/common.go deleted file mode 100644 index 13d8225f467a223f5d514b2f7920c158b1a2f649..0000000000000000000000000000000000000000 --- a/packages/binary/drng/subtypes/collectiveBeacon/payload/common.go +++ /dev/null @@ -1,8 +0,0 @@ -package payload - -const ( - // BLS Signature size in bytes. - SignatureSize = 96 - // BLS Public Key size in bytes. - PublicKeySize = 48 -) diff --git a/packages/binary/drng/subtypes/collectiveBeacon/collective_beacon.go b/packages/binary/drng/subtypes/collectivebeacon/collective_beacon.go similarity index 79% rename from packages/binary/drng/subtypes/collectiveBeacon/collective_beacon.go rename to packages/binary/drng/subtypes/collectivebeacon/collective_beacon.go index c539e6e37f0c97800a56e4f777ff993918054aac..ad0fa8da147d0bd8496ed290d285bc724e350561 100644 --- a/packages/binary/drng/subtypes/collectiveBeacon/collective_beacon.go +++ b/packages/binary/drng/subtypes/collectivebeacon/collective_beacon.go @@ -1,4 +1,4 @@ -package collectiveBeacon +package collectivebeacon import ( "bytes" @@ -8,17 +8,23 @@ import ( "github.com/drand/drand/beacon" "github.com/drand/drand/key" "github.com/iotaledger/goshimmer/packages/binary/drng/state" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/events" "github.com/iotaledger/hive.go/crypto/ed25519" ) var ( + // ErrDistributedPubKeyMismatch is returned if the distributed public key does not match. ErrDistributedPubKeyMismatch = errors.New("Distributed Public Key does not match") - ErrInvalidRound = errors.New("Invalid Round") - ErrInstanceIdMismatch = errors.New("InstanceID does not match") - ErrInvalidIssuer = errors.New("Invalid Issuer") - ErrNilState = errors.New("Nil state") - ErrNilData = errors.New("Nil data") + // ErrInvalidRound is returned if the round is invalid. + ErrInvalidRound = errors.New("Invalid Round") + // ErrInstanceIDMismatch is returned if the instanceID does not match. + ErrInstanceIDMismatch = errors.New("InstanceID does not match") + // ErrInvalidIssuer is returned if the issuer is invalid. + ErrInvalidIssuer = errors.New("Invalid Issuer") + // ErrNilState is returned on nil state. + ErrNilState = errors.New("Nil state") + // ErrNilData is returned on nil data. + ErrNilData = errors.New("Nil data") ) // ProcessBeacon performs the following tasks: @@ -73,7 +79,7 @@ func VerifyCollectiveBeacon(state *state.State, data *events.CollectiveBeaconEve } if data.InstanceID != state.Committee().InstanceID { - return ErrInstanceIdMismatch + return ErrInstanceIDMismatch } if err := verifySignature(data); err != nil { diff --git a/packages/binary/drng/subtypes/collectiveBeacon/collective_beacon_test.go b/packages/binary/drng/subtypes/collectivebeacon/collective_beacon_test.go similarity index 98% rename from packages/binary/drng/subtypes/collectiveBeacon/collective_beacon_test.go rename to packages/binary/drng/subtypes/collectivebeacon/collective_beacon_test.go index 62d991fb9ebcb1ff1ddc4965f53948194f749114..999d11aa57d144b62b97e502c508c62377325060 100644 --- a/packages/binary/drng/subtypes/collectiveBeacon/collective_beacon_test.go +++ b/packages/binary/drng/subtypes/collectivebeacon/collective_beacon_test.go @@ -1,4 +1,4 @@ -package collectiveBeacon +package collectivebeacon import ( "encoding/hex" @@ -10,8 +10,8 @@ import ( "github.com/drand/kyber/share" "github.com/drand/kyber/util/random" "github.com/iotaledger/goshimmer/packages/binary/drng/state" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/events" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/events" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/stretchr/testify/require" ) diff --git a/packages/binary/drng/subtypes/collectiveBeacon/events/events.go b/packages/binary/drng/subtypes/collectivebeacon/events/events.go similarity index 100% rename from packages/binary/drng/subtypes/collectiveBeacon/events/events.go rename to packages/binary/drng/subtypes/collectivebeacon/events/events.go diff --git a/packages/binary/drng/subtypes/collectiveBeacon/events/events_test.go b/packages/binary/drng/subtypes/collectivebeacon/events/events_test.go similarity index 100% rename from packages/binary/drng/subtypes/collectiveBeacon/events/events_test.go rename to packages/binary/drng/subtypes/collectivebeacon/events/events_test.go diff --git a/packages/binary/drng/subtypes/collectivebeacon/payload/common.go b/packages/binary/drng/subtypes/collectivebeacon/payload/common.go new file mode 100644 index 0000000000000000000000000000000000000000..810713c4501d1e2226c816811b17db914dfec5f8 --- /dev/null +++ b/packages/binary/drng/subtypes/collectivebeacon/payload/common.go @@ -0,0 +1,8 @@ +package payload + +const ( + // SignatureSize defines the BLS Signature size in bytes. + SignatureSize = 96 + // PublicKeySize defines the BLS Public Key size in bytes. + PublicKeySize = 48 +) diff --git a/packages/binary/drng/subtypes/collectiveBeacon/payload/payload.go b/packages/binary/drng/subtypes/collectivebeacon/payload/payload.go similarity index 95% rename from packages/binary/drng/subtypes/collectiveBeacon/payload/payload.go rename to packages/binary/drng/subtypes/collectivebeacon/payload/payload.go index 435ba79e339bcf4935d578a267b065b32a6275bd..25644f371bd0fa29e01732ff8770ae9a1cb8ff0b 100644 --- a/packages/binary/drng/subtypes/collectiveBeacon/payload/payload.go +++ b/packages/binary/drng/subtypes/collectivebeacon/payload/payload.go @@ -108,6 +108,7 @@ func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, return } +// Bytes returns the collective beacon payload bytes. func (payload *Payload) Bytes() (bytes []byte) { // acquire lock for reading bytes payload.bytesMutex.RLock() @@ -160,14 +161,17 @@ func (payload *Payload) String() string { // region Payload implementation /////////////////////////////////////////////////////////////////////////////////////// +// Type returns the collective beacon payload type. func (payload *Payload) Type() payload.Type { return drngPayload.Type } +// Marshal marshals the collective beacon payload into bytes. func (payload *Payload) Marshal() (bytes []byte, err error) { return payload.Bytes(), nil } +// Unmarshal returns a collective beacon payload from the given bytes. func (payload *Payload) Unmarshal(data []byte) (err error) { _, _, err = FromBytes(data, payload) diff --git a/packages/binary/drng/subtypes/collectiveBeacon/payload/payload_test.go b/packages/binary/drng/subtypes/collectivebeacon/payload/payload_test.go similarity index 100% rename from packages/binary/drng/subtypes/collectiveBeacon/payload/payload_test.go rename to packages/binary/drng/subtypes/collectivebeacon/payload/payload_test.go diff --git a/packages/binary/messagelayer/message/id.go b/packages/binary/messagelayer/message/id.go index 2dfd4f2856498d5dae24551288aa82b2d3936815..028ede7c0407526b4a560d72b7f0e17ff6429829 100644 --- a/packages/binary/messagelayer/message/id.go +++ b/packages/binary/messagelayer/message/id.go @@ -7,21 +7,21 @@ import ( "github.com/mr-tron/base58" ) -// ContentId identifies the content of a message without its trunk/branch ids. -type ContentId = Id +// ContentID identifies the content of a message without its trunk/branch ids. +type ContentID = ID // ID identifies a message in its entirety. Unlike the sole content id, it also incorporates // the trunk and branch ids. -type Id [IdLength]byte +type ID [IDLength]byte -// NewId creates a new message id. -func NewId(base58EncodedString string) (result Id, err error) { +// NewID creates a new message id. +func NewID(base58EncodedString string) (result ID, err error) { bytes, err := base58.Decode(base58EncodedString) if err != nil { return } - if len(bytes) != IdLength { + if len(bytes) != IDLength { err = fmt.Errorf("length of base58 formatted message id is wrong") return @@ -32,10 +32,10 @@ func NewId(base58EncodedString string) (result Id, err error) { return } -// IdFromBytes unmarshals a message id from a sequence of bytes. -func IdFromBytes(bytes []byte) (result Id, consumedBytes int, err error) { +// IDFromBytes unmarshals a message id from a sequence of bytes. +func IDFromBytes(bytes []byte) (result ID, consumedBytes int, err error) { // check arguments - if len(bytes) < IdLength { + if len(bytes) < IDLength { err = fmt.Errorf("bytes not long enough to encode a valid message id") } @@ -43,38 +43,44 @@ func IdFromBytes(bytes []byte) (result Id, consumedBytes int, err error) { copy(result[:], bytes) // return the number of bytes we processed - consumedBytes = IdLength + consumedBytes = IDLength return } -// ParseId is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package. -func ParseId(marshalUtil *marshalutil.MarshalUtil) (Id, error) { - if id, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return IdFromBytes(data) }); err != nil { - return Id{}, err - } else { - return id.(Id), nil +// ParseID is a wrapper for simplified unmarshaling in a byte stream using the marshalUtil package. +func ParseID(marshalUtil *marshalutil.MarshalUtil) (ID, error) { + id, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return IDFromBytes(data) }) + if err != nil { + return ID{}, err } + return id.(ID), nil } -func (id *Id) MarshalBinary() (result []byte, err error) { +// MarshalBinary marshals the ID into bytes. +func (id *ID) MarshalBinary() (result []byte, err error) { return id.Bytes(), nil } -func (id *Id) UnmarshalBinary(data []byte) (err error) { +// UnmarshalBinary unmarshals the bytes into an ID. +func (id *ID) UnmarshalBinary(data []byte) (err error) { copy(id[:], data) return } -func (id Id) Bytes() []byte { +// Bytes returns the bytes of the ID. +func (id ID) Bytes() []byte { return id[:] } -func (id Id) String() string { +// String returns the base58 encode of the ID. +func (id ID) String() string { return base58.Encode(id[:]) } -var EmptyId = Id{} +// EmptyID is an empty id. +var EmptyID = ID{} -const IdLength = 64 +// IDLength defines the length of an ID. +const IDLength = 64 diff --git a/packages/binary/messagelayer/message/message.go b/packages/binary/messagelayer/message/message.go index 6415cacba10e56ca2f779f08532a92f73842262e..e987851b4684484bc66b5f528bb8acbe2b16b513 100644 --- a/packages/binary/messagelayer/message/message.go +++ b/packages/binary/messagelayer/message/message.go @@ -19,8 +19,8 @@ type Message struct { objectstorage.StorableObjectFlags // core properties (get sent over the wire) - trunkID Id - branchID Id + trunkID ID + branchID ID issuerPublicKey ed25519.PublicKey issuingTime time.Time sequenceNumber uint64 @@ -29,16 +29,16 @@ type Message struct { signature ed25519.Signature // derived properties - id *Id + id *ID idMutex sync.RWMutex - contentId *ContentId - contentIdMutex sync.RWMutex + contentID *ContentID + contentIDMutex sync.RWMutex bytes []byte bytesMutex sync.RWMutex } // New creates a new message with the details provided by the issuer. -func New(trunkID Id, branchID Id, issuingTime time.Time, issuerPublicKey ed25519.PublicKey, sequenceNumber uint64, payload payload.Payload, nonce uint64, signature ed25519.Signature) (result *Message) { +func New(trunkID ID, branchID ID, issuingTime time.Time, issuerPublicKey ed25519.PublicKey, sequenceNumber uint64, payload payload.Payload, nonce uint64, signature ed25519.Signature) (result *Message) { return &Message{ trunkID: trunkID, branchID: branchID, @@ -52,7 +52,7 @@ func New(trunkID Id, branchID Id, issuingTime time.Time, issuerPublicKey ed25519 } // FromBytes parses the given bytes into a message. -func FromBytes(bytes []byte, optionalTargetObject ...*Message) (result *Message, err error, consumedBytes int) { +func FromBytes(bytes []byte, optionalTargetObject ...*Message) (result *Message, consumedBytes int, err error) { marshalUtil := marshalutil.New(bytes) result, err = Parse(marshalUtil, optionalTargetObject...) consumedBytes = marshalUtil.ReadOffset() @@ -94,13 +94,13 @@ func StorableObjectFromKey(key []byte, optionalTargetObject ...*Message) (result } marshalUtil := marshalutil.New(key) - if id, idErr := ParseId(marshalUtil); idErr != nil { + id, idErr := ParseID(marshalUtil) + if idErr != nil { err = idErr return - } else { - result.(*Message).id = &id } + result.(*Message).id = &id consumedBytes = marshalUtil.ReadOffset() return @@ -119,7 +119,7 @@ func (message *Message) VerifySignature() bool { // ID returns the id of the message which is made up of the content id and trunk/branch ids. // This id can be used for merkle proofs. -func (message *Message) Id() (result Id) { +func (message *Message) ID() (result ID) { message.idMutex.RLock() if message.id == nil { @@ -131,7 +131,7 @@ func (message *Message) Id() (result Id) { result = *message.id return } - result = message.calculateId() + result = message.calculateID() message.id = &result return } @@ -142,12 +142,12 @@ func (message *Message) Id() (result Id) { } // TrunkID returns the id of the trunk message. -func (message *Message) TrunkId() Id { +func (message *Message) TrunkID() ID { return message.trunkID } // BranchID returns the id of the branch message. -func (message *Message) BranchId() Id { +func (message *Message) BranchID() ID { return message.branchID } @@ -171,7 +171,7 @@ func (message *Message) Payload() payload.Payload { return message.payload } -// Payload returns the payload of the message. +// Nonce returns the nonce of the message. func (message *Message) Nonce() uint64 { return message.nonce } @@ -181,44 +181,44 @@ func (message *Message) Signature() ed25519.Signature { return message.signature } -// ContentId returns the content id of the message which is made up of all the +// ContentID returns the content id of the message which is made up of all the // parts of the message minus the trunk and branch ids. -func (message *Message) ContentId() (result ContentId) { - message.contentIdMutex.RLock() - if message.contentId == nil { - message.contentIdMutex.RUnlock() - - message.contentIdMutex.Lock() - defer message.contentIdMutex.Unlock() - if message.contentId != nil { - result = *message.contentId +func (message *Message) ContentID() (result ContentID) { + message.contentIDMutex.RLock() + if message.contentID == nil { + message.contentIDMutex.RUnlock() + + message.contentIDMutex.Lock() + defer message.contentIDMutex.Unlock() + if message.contentID != nil { + result = *message.contentID return } - result = message.calculateContentId() - message.contentId = &result + result = message.calculateContentID() + message.contentID = &result return } - result = *message.contentId - message.contentIdMutex.RUnlock() + result = *message.contentID + message.contentIDMutex.RUnlock() return } // calculates the message id. -func (message *Message) calculateId() Id { +func (message *Message) calculateID() ID { return blake2b.Sum512( - marshalutil.New(IdLength + IdLength + payload.IdLength). + marshalutil.New(IDLength + IDLength + payload.IDLength). WriteBytes(message.trunkID.Bytes()). WriteBytes(message.branchID.Bytes()). - WriteBytes(message.ContentId().Bytes()). + WriteBytes(message.ContentID().Bytes()). Bytes(), ) } // calculates the content id of the message. -func (message *Message) calculateContentId() ContentId { +func (message *Message) calculateContentID() ContentID { // compute content id from the message data (except trunk and branch ids) - return blake2b.Sum512(message.Bytes()[2*IdLength:]) + return blake2b.Sum512(message.Bytes()[2*IDLength:]) } // Bytes returns the message in serialized byte form. @@ -254,15 +254,16 @@ func (message *Message) Bytes() []byte { return message.bytes } +// UnmarshalObjectStorageValue unmarshals the bytes into a message. func (message *Message) UnmarshalObjectStorageValue(data []byte) (consumedBytes int, err error) { // initialize helper marshalUtil := marshalutil.New(data) // parse information - if message.trunkID, err = ParseId(marshalUtil); err != nil { + if message.trunkID, err = ParseID(marshalUtil); err != nil { return } - if message.branchID, err = ParseId(marshalUtil); err != nil { + if message.branchID, err = ParseID(marshalUtil); err != nil { return } if message.issuerPublicKey, err = ed25519.ParsePublicKey(marshalUtil); err != nil { @@ -294,11 +295,14 @@ func (message *Message) UnmarshalObjectStorageValue(data []byte) (consumedBytes return } +// ObjectStorageKey returns the key of the stored message object. +// This returns the bytes of the message ID. func (message *Message) ObjectStorageKey() []byte { - return message.Id().Bytes() + return message.ID().Bytes() } -// Since messages are immutable and do not get changed after being created, we cache the result of the marshaling. +// ObjectStorageValue returns the value stored in object storage. +// This returns the bytes of message. func (message *Message) ObjectStorageValue() []byte { return message.Bytes() } @@ -311,9 +315,9 @@ func (message *Message) Update(objectstorage.StorableObject) { func (message *Message) String() string { return stringify.Struct("Message", - stringify.StructField("id", message.Id()), - stringify.StructField("trunkId", message.TrunkId()), - stringify.StructField("branchId", message.BranchId()), + stringify.StructField("id", message.ID()), + stringify.StructField("trunkId", message.TrunkID()), + stringify.StructField("branchId", message.BranchID()), stringify.StructField("issuer", message.IssuerPublicKey()), stringify.StructField("issuingTime", message.IssuingTime()), stringify.StructField("sequenceNumber", message.SequenceNumber()), @@ -323,28 +327,35 @@ func (message *Message) String() string { ) } +// CachedMessage defines a cached message. +// A wrapper for a cached object. type CachedMessage struct { objectstorage.CachedObject } +// Retain registers a new consumer for the cached message. func (cachedMessage *CachedMessage) Retain() *CachedMessage { return &CachedMessage{cachedMessage.CachedObject.Retain()} } +// Consume consumes the cached object and releases it when the callback is done. +// It returns true if the callback was called. func (cachedMessage *CachedMessage) Consume(consumer func(msg *Message)) bool { return cachedMessage.CachedObject.Consume(func(object objectstorage.StorableObject) { consumer(object.(*Message)) }) } +// Unwrap returns the message wrapped by the cached message. +// If the wrapped object cannot be cast to a Message or has been deleted, it returns nil. func (cachedMessage *CachedMessage) Unwrap() *Message { - if untypedMessage := cachedMessage.Get(); untypedMessage == nil { + untypedMessage := cachedMessage.Get() + if untypedMessage == nil { + return nil + } + typeCastedMessage := untypedMessage.(*Message) + if typeCastedMessage == nil || typeCastedMessage.IsDeleted() { return nil - } else { - if typeCastedMessage := untypedMessage.(*Message); typeCastedMessage == nil || typeCastedMessage.IsDeleted() { - return nil - } else { - return typeCastedMessage - } } + return typeCastedMessage } diff --git a/packages/binary/messagelayer/messagefactory/messagefactory.go b/packages/binary/messagelayer/messagefactory/messagefactory.go index 82311b0053de3dd3b8df91bb914706ea38af290f..5240e3faf086d9a9fc4fafb0c09cde6917bbdf5a 100644 --- a/packages/binary/messagelayer/messagefactory/messagefactory.go +++ b/packages/binary/messagelayer/messagefactory/messagefactory.go @@ -21,7 +21,7 @@ var ( // A TipSelector selects two tips, branch and trunk, for a new message to attach to. type TipSelector interface { - Tips() (trunk message.Id, branch message.Id) + Tips() (trunk message.ID, branch message.ID) } // A Worker performs the PoW for the provided message in serialized byte form. @@ -120,7 +120,7 @@ func (m *MessageFactory) Shutdown() { } } -func (m *MessageFactory) doPOW(trunkID message.Id, branchID message.Id, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload) (uint64, error) { +func (m *MessageFactory) doPOW(trunkID message.ID, branchID message.ID, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload) (uint64, error) { // create a dummy message to simplify marshaling dummy := message.New(trunkID, branchID, issuingTime, key, seq, payload, 0, ed25519.EmptySignature).Bytes() @@ -129,7 +129,7 @@ func (m *MessageFactory) doPOW(trunkID message.Id, branchID message.Id, issuingT return m.worker.DoPOW(dummy) } -func (m *MessageFactory) sign(trunkID message.Id, branchID message.Id, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload, nonce uint64) ed25519.Signature { +func (m *MessageFactory) sign(trunkID message.ID, branchID message.ID, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload, nonce uint64) ed25519.Signature { // create a dummy message to simplify marshaling dummy := message.New(trunkID, branchID, issuingTime, key, seq, payload, nonce, ed25519.EmptySignature) dummyBytes := dummy.Bytes() @@ -139,10 +139,10 @@ func (m *MessageFactory) sign(trunkID message.Id, branchID message.Id, issuingTi } // The TipSelectorFunc type is an adapter to allow the use of ordinary functions as tip selectors. -type TipSelectorFunc func() (message.Id, message.Id) +type TipSelectorFunc func() (message.ID, message.ID) // Tips calls f(). -func (f TipSelectorFunc) Tips() (message.Id, message.Id) { +func (f TipSelectorFunc) Tips() (message.ID, message.ID) { return f() } diff --git a/packages/binary/messagelayer/messagefactory/messagefactory_test.go b/packages/binary/messagelayer/messagefactory/messagefactory_test.go index 5d56750babeda1a628753fc90ec527d378129c69..e53ffd3ab12f6d8ac90d640fa22605af61d41ac4 100644 --- a/packages/binary/messagelayer/messagefactory/messagefactory_test.go +++ b/packages/binary/messagelayer/messagefactory/messagefactory_test.go @@ -31,7 +31,7 @@ func TestMessageFactory_BuildMessage(t *testing.T) { mapdb.NewMapDB(), []byte(sequenceKey), identity.GenerateLocalIdentity(), - TipSelectorFunc(func() (message.Id, message.Id) { return message.EmptyId, message.EmptyId }), + TipSelectorFunc(func() (message.ID, message.ID) { return message.EmptyID, message.EmptyID }), ) defer msgFactory.Shutdown() @@ -49,8 +49,8 @@ func TestMessageFactory_BuildMessage(t *testing.T) { msg, err := msgFactory.IssuePayload(p) require.NoError(t, err) - assert.NotNil(t, msg.TrunkId()) - assert.NotNil(t, msg.BranchId()) + assert.NotNil(t, msg.TrunkID()) + assert.NotNil(t, msg.BranchID()) // time in range of 0.1 seconds assert.InDelta(t, time.Now().UnixNano(), msg.IssuingTime().UnixNano(), 100000000) @@ -75,8 +75,8 @@ func TestMessageFactory_BuildMessage(t *testing.T) { msg, err := msgFactory.IssuePayload(p) require.NoError(t, err) - assert.NotNil(t, msg.TrunkId()) - assert.NotNil(t, msg.BranchId()) + assert.NotNil(t, msg.TrunkID()) + assert.NotNil(t, msg.BranchID()) // time in range of 0.1 seconds assert.InDelta(t, time.Now().UnixNano(), msg.IssuingTime().UnixNano(), 100000000) @@ -117,7 +117,7 @@ func TestMessageFactory_POW(t *testing.T) { mapdb.NewMapDB(), []byte(sequenceKey), identity.GenerateLocalIdentity(), - TipSelectorFunc(func() (message.Id, message.Id) { return message.EmptyId, message.EmptyId }), + TipSelectorFunc(func() (message.ID, message.ID) { return message.EmptyID, message.EmptyID }), ) defer msgFactory.Shutdown() @@ -144,7 +144,7 @@ func TestWorkerFunc_PayloadSize(t *testing.T) { mapdb.NewMapDB(), []byte(sequenceKey), identity.GenerateLocalIdentity(), - TipSelectorFunc(func() (message.Id, message.Id) { return message.EmptyId, message.EmptyId }), + TipSelectorFunc(func() (message.ID, message.ID) { return message.EmptyID, message.EmptyID }), ) defer msgFactory.Shutdown() diff --git a/packages/binary/messagelayer/messageparser/builtinfilters/pow_filter_test.go b/packages/binary/messagelayer/messageparser/builtinfilters/pow_filter_test.go index b348247bb28c6c5b4f7cf533492b5fa23b21af54..aec79fdd9134ad6fa3d8baee1b45aafa0c00f994 100644 --- a/packages/binary/messagelayer/messageparser/builtinfilters/pow_filter_test.go +++ b/packages/binary/messagelayer/messageparser/builtinfilters/pow_filter_test.go @@ -69,5 +69,5 @@ func (m *callbackMock) Accept(msg []byte, p *peer.Peer) { m.Called(ms func (m *callbackMock) Reject(msg []byte, err error, p *peer.Peer) { m.Called(msg, err, p) } func newTestMessage(nonce uint64) *message.Message { - return message.New(message.EmptyId, message.EmptyId, time.Time{}, ed25519.PublicKey{}, 0, testPayload, nonce, ed25519.Signature{}) + return message.New(message.EmptyID, message.EmptyID, time.Time{}, ed25519.PublicKey{}, 0, testPayload, nonce, ed25519.Signature{}) } diff --git a/packages/binary/messagelayer/messageparser/message_parser.go b/packages/binary/messagelayer/messageparser/message_parser.go index 9c590e63ff6fe81dcb30925ee0abd7498bc58d0f..8125095c65dab023ffd8877135ac41dd7d803d5b 100644 --- a/packages/binary/messagelayer/messageparser/message_parser.go +++ b/packages/binary/messagelayer/messageparser/message_parser.go @@ -124,7 +124,7 @@ func (messageParser *MessageParser) setupMessageFilterDataFlow() { // parses the given message and emits func (messageParser *MessageParser) parseMessage(bytes []byte, peer *peer.Peer) { - if parsedMessage, err, _ := message.FromBytes(bytes); err != nil { + if parsedMessage, _, err := message.FromBytes(bytes); err != nil { messageParser.Events.BytesRejected.Trigger(bytes, err, peer) } else { messageParser.messageFilters[0].Filter(parsedMessage, peer) diff --git a/packages/binary/messagelayer/messageparser/message_parser_test.go b/packages/binary/messagelayer/messageparser/message_parser_test.go index e85cf4cee9881f6902a2ff6f4de3e0e3c6e2a060..4f96612c0cf8c89c84d6702521dda9869320d0ec 100644 --- a/packages/binary/messagelayer/messageparser/message_parser_test.go +++ b/packages/binary/messagelayer/messageparser/message_parser_test.go @@ -51,5 +51,5 @@ func TestMessageParser_ParseMessage(t *testing.T) { } func newTestMessage(payloadString string) *message.Message { - return message.New(message.EmptyId, message.EmptyId, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) + return message.New(message.EmptyID, message.EmptyID, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) } diff --git a/packages/binary/messagelayer/messagerequester/messagerequester.go b/packages/binary/messagelayer/messagerequester/messagerequester.go index cc3dc7cd5e7855b88df105b71f3ccc0cf64bd358..8ad404abb40b1860f8e5325dfd37492174cc4a26 100644 --- a/packages/binary/messagelayer/messagerequester/messagerequester.go +++ b/packages/binary/messagelayer/messagerequester/messagerequester.go @@ -12,7 +12,7 @@ const messageExistCheckThreshold = 10 // MessageRequester takes care of requesting messages. type MessageRequester struct { - scheduledRequests map[message.Id]*time.Timer + scheduledRequests map[message.ID]*time.Timer options *Options messageExistsFunc MessageExistsFunc Events Events @@ -21,24 +21,24 @@ type MessageRequester struct { } // MessageExistsFunc is a function that tells if a message exists. -type MessageExistsFunc func(messageId message.Id) bool +type MessageExistsFunc func(messageId message.ID) bool -func createReRequest(requester *MessageRequester, msgID message.Id, count int) func() { +func createReRequest(requester *MessageRequester, msgID message.ID, count int) func() { return func() { requester.reRequest(msgID, count) } } // New creates a new message requester. -func New(messageExists MessageExistsFunc, missingMessages []message.Id, optionalOptions ...Option) *MessageRequester { +func New(messageExists MessageExistsFunc, missingMessages []message.ID, optionalOptions ...Option) *MessageRequester { requester := &MessageRequester{ - scheduledRequests: make(map[message.Id]*time.Timer), + scheduledRequests: make(map[message.ID]*time.Timer), options: newOptions(optionalOptions), messageExistsFunc: messageExists, Events: Events{ SendRequest: events.NewEvent(func(handler interface{}, params ...interface{}) { - handler.(func(message.Id))(params[0].(message.Id)) + handler.(func(message.ID))(params[0].(message.ID)) }), MissingMessageAppeared: events.NewEvent(func(handler interface{}, params ...interface{}) { - handler.(func(message.Id))(params[0].(message.Id)) + handler.(func(message.ID))(params[0].(message.ID)) }), }, } @@ -55,7 +55,7 @@ func New(messageExists MessageExistsFunc, missingMessages []message.Id, optional } // StartRequest initiates a regular triggering of the StartRequest event until it has been stopped using StopRequest. -func (requester *MessageRequester) StartRequest(id message.Id) { +func (requester *MessageRequester) StartRequest(id message.ID) { requester.scheduledRequestsMutex.Lock() // ignore already scheduled requests @@ -71,7 +71,7 @@ func (requester *MessageRequester) StartRequest(id message.Id) { } // StopRequest stops requests for the given message to further happen. -func (requester *MessageRequester) StopRequest(id message.Id) { +func (requester *MessageRequester) StopRequest(id message.ID) { requester.scheduledRequestsMutex.Lock() defer requester.scheduledRequestsMutex.Unlock() @@ -81,7 +81,7 @@ func (requester *MessageRequester) StopRequest(id message.Id) { } } -func (requester *MessageRequester) reRequest(id message.Id, count int) { +func (requester *MessageRequester) reRequest(id message.ID, count int) { requester.Events.SendRequest.Trigger(id) count++ diff --git a/packages/binary/messagelayer/payload/data.go b/packages/binary/messagelayer/payload/data.go index 9db9cc640b6e9f5114f94a5de8d042e640cc866a..26929cf79531dbadeb6511ccb855ff8dad9d52c5 100644 --- a/packages/binary/messagelayer/payload/data.go +++ b/packages/binary/messagelayer/payload/data.go @@ -23,7 +23,7 @@ func NewData(data []byte) *Data { } // DataFromBytes creates a new data payload from the given bytes. -func DataFromBytes(bytes []byte, optionalTargetObject ...*Data) (result *Data, err error, consumedBytes int) { +func DataFromBytes(bytes []byte, optionalTargetObject ...*Data) (result *Data, consumedBytes int, err error) { marshalUtil := marshalutil.New(bytes) result, err = ParseData(marshalUtil, optionalTargetObject...) consumedBytes = marshalUtil.ReadOffset() @@ -60,6 +60,7 @@ func ParseData(marshalUtil *marshalutil.MarshalUtil, optionalTargetObject ...*Da return } +// Type returns the payload type. func (dataPayload *Data) Type() Type { return dataPayload.payloadType } @@ -83,8 +84,9 @@ func (dataPayload *Data) Bytes() []byte { return marshalUtil.Bytes() } +// Unmarshal unmarshalls the byte array to a data payload. func (dataPayload *Data) Unmarshal(data []byte) (err error) { - _, err, _ = DataFromBytes(data, dataPayload) + _, _, err = DataFromBytes(data, dataPayload) return } diff --git a/packages/binary/messagelayer/payload/id.go b/packages/binary/messagelayer/payload/id.go index 1320572d1822cd2cd1af25f7628f22519b6ad5e8..ca5bc407e6f47600f201ea04ec9aa625306a8003 100644 --- a/packages/binary/messagelayer/payload/id.go +++ b/packages/binary/messagelayer/payload/id.go @@ -3,17 +3,17 @@ package payload import "github.com/mr-tron/base58" // ID represents the id of a data payload. -type Id [IdLength]byte +type ID [IDLength]byte // Bytes returns the id as a byte slice backed by the original array, // therefore it should not be modified. -func (id Id) Bytes() []byte { +func (id ID) Bytes() []byte { return id[:] } -func (id Id) String() string { +func (id ID) String() string { return base58.Encode(id[:]) } -// IdLength is the length of a data payload id. -const IdLength = 64 +// IDLength is the length of a data payload id. +const IDLength = 64 diff --git a/packages/binary/messagelayer/payload/payload.go b/packages/binary/messagelayer/payload/payload.go index 689acbf7c5e48c279b36c54534d0b51e1d2f2b23..b86da5b463b826b60fd7d5a243f5c9d97d3373f0 100644 --- a/packages/binary/messagelayer/payload/payload.go +++ b/packages/binary/messagelayer/payload/payload.go @@ -88,9 +88,9 @@ func FromBytes(bytes []byte) (result Payload, consumedBytes int, err error) { // Parse parses a payload by using the given marshal util. func Parse(marshalUtil *marshalutil.MarshalUtil) (Payload, error) { - if payload, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return FromBytes(data) }); err != nil { + payload, err := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return FromBytes(data) }) + if err != nil { return nil, err - } else { - return payload.(Payload), nil } + return payload.(Payload), nil } diff --git a/packages/binary/messagelayer/tangle/approver.go b/packages/binary/messagelayer/tangle/approver.go index 5526a104b2bb2a39595c2ddff22665164fd984b3..8dc3a6ff8ef4ff7640f09a31410e4b60ecfd05f2 100644 --- a/packages/binary/messagelayer/tangle/approver.go +++ b/packages/binary/messagelayer/tangle/approver.go @@ -12,22 +12,22 @@ import ( type Approver struct { objectstorage.StorableObjectFlags // the message which got referenced by the approver message. - referencedMessageId message.Id + referencedMessageID message.ID // the message which approved/referenced the given referenced message. - approverMessageId message.Id + approverMessageID message.ID } // NewApprover creates a new approver relation to the given approved/referenced message. -func NewApprover(referencedMessageId message.Id, approverMessageId message.Id) *Approver { +func NewApprover(referencedMessageID message.ID, approverMessageID message.ID) *Approver { approver := &Approver{ - referencedMessageId: referencedMessageId, - approverMessageId: approverMessageId, + referencedMessageID: referencedMessageID, + approverMessageID: approverMessageID, } return approver } // ApproverFromBytes parses the given bytes into an approver. -func ApproverFromBytes(bytes []byte, optionalTargetObject ...*Approver) (result *Approver, err error, consumedBytes int) { +func ApproverFromBytes(bytes []byte, optionalTargetObject ...*Approver) (result *Approver, consumedBytes int, err error) { marshalUtil := marshalutil.New(bytes) result, err = ParseApprover(marshalUtil, optionalTargetObject...) consumedBytes = marshalUtil.ReadOffset() @@ -36,14 +36,14 @@ func ApproverFromBytes(bytes []byte, optionalTargetObject ...*Approver) (result // ParseApprover parses a new approver from the given marshal util. func ParseApprover(marshalUtil *marshalutil.MarshalUtil, optionalTargetObject ...*Approver) (result *Approver, err error) { - if parsedObject, parseErr := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { + parsedObject, parseErr := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return ApproverFromStorageKey(data, optionalTargetObject...) - }); parseErr != nil { + }) + if parseErr != nil { err = parseErr return - } else { - result = parsedObject.(*Approver) } + result = parsedObject.(*Approver) _, err = marshalUtil.Parse(func(data []byte) (parseResult interface{}, parsedBytes int, parseErr error) { parsedBytes, parseErr = result.UnmarshalObjectStorageValue(data) @@ -68,10 +68,10 @@ func ApproverFromStorageKey(key []byte, optionalTargetObject ...*Approver) (resu // parse the properties that are stored in the key marshalUtil := marshalutil.New(key) - if result.(*Approver).referencedMessageId, err = message.ParseId(marshalUtil); err != nil { + if result.(*Approver).referencedMessageID, err = message.ParseID(marshalUtil); err != nil { return } - if result.(*Approver).approverMessageId, err = message.ParseId(marshalUtil); err != nil { + if result.(*Approver).approverMessageID, err = message.ParseID(marshalUtil); err != nil { return } consumedBytes = marshalUtil.ReadOffset() @@ -79,42 +79,50 @@ func ApproverFromStorageKey(key []byte, optionalTargetObject ...*Approver) (resu return } -// ReferencedMessageId returns the id of the message which is referenced by the approver. -func (approver *Approver) ReferencedMessageId() message.Id { - return approver.referencedMessageId +// ReferencedMessageID returns the ID of the message which is referenced by the approver. +func (approver *Approver) ReferencedMessageID() message.ID { + return approver.referencedMessageID } -// ApproverMessageId returns the id of the message which referenced the given approved message. -func (approver *Approver) ApproverMessageId() message.Id { - return approver.approverMessageId +// ApproverMessageID returns the ID of the message which referenced the given approved message. +func (approver *Approver) ApproverMessageID() message.ID { + return approver.approverMessageID } +// Bytes returns the bytes of the approver. func (approver *Approver) Bytes() []byte { return approver.ObjectStorageKey() } +// String returns the string representation of the approver. func (approver *Approver) String() string { return stringify.Struct("Approver", - stringify.StructField("referencedMessageId", approver.ReferencedMessageId()), - stringify.StructField("approverMessageId", approver.ApproverMessageId()), + stringify.StructField("referencedMessageID", approver.ReferencedMessageID()), + stringify.StructField("approverMessageID", approver.ApproverMessageID()), ) } +// ObjectStorageKey marshals the keys of the stored approver into a byte array. +// This includes the referencedMessageID and the approverMessageID. func (approver *Approver) ObjectStorageKey() []byte { return marshalutil.New(). - WriteBytes(approver.referencedMessageId.Bytes()). - WriteBytes(approver.approverMessageId.Bytes()). + WriteBytes(approver.referencedMessageID.Bytes()). + WriteBytes(approver.approverMessageID.Bytes()). Bytes() } +// ObjectStorageValue returns the value of the stored approver object. func (approver *Approver) ObjectStorageValue() (result []byte) { return } +// UnmarshalObjectStorageValue unmarshals the stored bytes into an approver. func (approver *Approver) UnmarshalObjectStorageValue(data []byte) (consumedBytes int, err error) { return } +// Update updates the approver. +// This should should never happen and will panic if attempted. func (approver *Approver) Update(other objectstorage.StorableObject) { panic("approvers should never be overwritten and only stored once to optimize IO") } @@ -122,10 +130,13 @@ func (approver *Approver) Update(other objectstorage.StorableObject) { // interface contract (allow the compiler to check if the implementation has all of the required methods). var _ objectstorage.StorableObject = &Approver{} +// CachedApprover is a wrapper for a stored cached object representing an approver. type CachedApprover struct { objectstorage.CachedObject } +// Unwrap unwraps the cached approver into the underlying approver. +// If stored object cannot be cast into an approver or has been deleted, it returns nil. func (cachedApprover *CachedApprover) Unwrap() *Approver { untypedObject := cachedApprover.Get() if untypedObject == nil { @@ -141,14 +152,19 @@ func (cachedApprover *CachedApprover) Unwrap() *Approver { } +// Consume consumes the cachedApprover. +// It releases the object when the callback is done. +// It returns true if the callback was called. func (cachedApprover *CachedApprover) Consume(consumer func(approver *Approver)) (consumed bool) { return cachedApprover.CachedObject.Consume(func(object objectstorage.StorableObject) { consumer(object.(*Approver)) }) } +// CachedApprovers defines a slice of *CachedApprover. type CachedApprovers []*CachedApprover +// Consume calls *CachedApprover.Consume on element in the list. func (cachedApprovers CachedApprovers) Consume(consumer func(approver *Approver)) (consumed bool) { for _, cachedApprover := range cachedApprovers { consumed = cachedApprover.Consume(func(approver *Approver) { diff --git a/packages/binary/messagelayer/tangle/events.go b/packages/binary/messagelayer/tangle/events.go index 399d28002aa5ecec6336a9ec20b2efa1fd911770..6e8f0519a0225d72f8e58359abc7b27526aba6b0 100644 --- a/packages/binary/messagelayer/tangle/events.go +++ b/packages/binary/messagelayer/tangle/events.go @@ -29,14 +29,14 @@ func newEvents() *Events { MessageAttached: events.NewEvent(cachedMessageEvent), MessageSolid: events.NewEvent(cachedMessageEvent), MissingMessageReceived: events.NewEvent(cachedMessageEvent), - MessageMissing: events.NewEvent(messageIdEvent), - MessageUnsolidifiable: events.NewEvent(messageIdEvent), - MessageRemoved: events.NewEvent(messageIdEvent), + MessageMissing: events.NewEvent(messageIDEvent), + MessageUnsolidifiable: events.NewEvent(messageIDEvent), + MessageRemoved: events.NewEvent(messageIDEvent), } } -func messageIdEvent(handler interface{}, params ...interface{}) { - handler.(func(message.Id))(params[0].(message.Id)) +func messageIDEvent(handler interface{}, params ...interface{}) { + handler.(func(message.ID))(params[0].(message.ID)) } func cachedMessageEvent(handler interface{}, params ...interface{}) { diff --git a/packages/binary/messagelayer/tangle/messagemetadata.go b/packages/binary/messagelayer/tangle/messagemetadata.go index 9285ef78d9b4417d209afecdf802e3443fc7f3d3..e9ea71263a6f0ee843b9a26da76a40d6b1c95970 100644 --- a/packages/binary/messagelayer/tangle/messagemetadata.go +++ b/packages/binary/messagelayer/tangle/messagemetadata.go @@ -10,10 +10,11 @@ import ( "github.com/iotaledger/goshimmer/packages/binary/messagelayer/message" ) +// MessageMetadata defines the metadata for a message. type MessageMetadata struct { objectstorage.StorableObjectFlags - messageId message.Id + messageID message.ID receivedTime time.Time solid bool solidificationTime time.Time @@ -22,14 +23,16 @@ type MessageMetadata struct { solidificationTimeMutex sync.RWMutex } -func NewMessageMetadata(messageId message.Id) *MessageMetadata { +// NewMessageMetadata creates a new MessageMetadata from the specified messageID. +func NewMessageMetadata(messageID message.ID) *MessageMetadata { return &MessageMetadata{ - messageId: messageId, + messageID: messageID, receivedTime: time.Now(), } } -func MessageMetadataFromBytes(bytes []byte) (result *MessageMetadata, err error, consumedBytes int) { +// MessageMetadataFromBytes unmarshals the given bytes into a MessageMetadata. +func MessageMetadataFromBytes(bytes []byte) (result *MessageMetadata, consumedBytes int, err error) { marshalUtil := marshalutil.New(bytes) result, err = ParseMessageMetadata(marshalUtil) consumedBytes = marshalUtil.ReadOffset() @@ -37,17 +40,18 @@ func MessageMetadataFromBytes(bytes []byte) (result *MessageMetadata, err error, return } +// ParseMessageMetadata parses the marshalUtil into a MessageMetadata. +// If it successfully parses the marshalUtil, it delegates to MessageMetadataFromStorageKey. +// Else, delegates to UnmarshalObjectStorageValue. func ParseMessageMetadata(marshalUtil *marshalutil.MarshalUtil) (result *MessageMetadata, err error) { - if parsedObject, parseErr := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { + parsedObject, parseErr := marshalUtil.Parse(func(data []byte) (interface{}, int, error) { return MessageMetadataFromStorageKey(data) - }); parseErr != nil { + }) + if parseErr != nil { err = parseErr - return - } else { - result = parsedObject.(*MessageMetadata) } - + result = parsedObject.(*MessageMetadata) _, err = marshalUtil.Parse(func(data []byte) (parseResult interface{}, parsedBytes int, parseErr error) { parsedBytes, parseErr = result.UnmarshalObjectStorageValue(data) @@ -57,11 +61,12 @@ func ParseMessageMetadata(marshalUtil *marshalutil.MarshalUtil) (result *Message return } +// MessageMetadataFromStorageKey unmarshals the stored bytes into a MessageMetadata. func MessageMetadataFromStorageKey(key []byte) (result objectstorage.StorableObject, consumedBytes int, err error) { result = &MessageMetadata{} marshalUtil := marshalutil.New(key) - result.(*MessageMetadata).messageId, err = message.ParseId(marshalUtil) + result.(*MessageMetadata).messageID, err = message.ParseID(marshalUtil) if err != nil { return } @@ -75,6 +80,7 @@ func (messageMetadata *MessageMetadata) ReceivedTime() time.Time { return messageMetadata.receivedTime } +// IsSolid returns true if the message represented by this metadata is solid. False otherwise. func (messageMetadata *MessageMetadata) IsSolid() (result bool) { messageMetadata.solidMutex.RLock() result = messageMetadata.solid @@ -83,6 +89,8 @@ func (messageMetadata *MessageMetadata) IsSolid() (result bool) { return } +// SetSolid sets the message associated with this metadata as solid. +// It returns true if the solid status is modified. False otherwise. func (messageMetadata *MessageMetadata) SetSolid(solid bool) (modified bool) { messageMetadata.solidMutex.RLock() if messageMetadata.solid != solid { @@ -118,10 +126,14 @@ func (messageMetadata *MessageMetadata) SolidificationTime() time.Time { return messageMetadata.solidificationTime } +// ObjectStorageKey returns the key of the stored message metadata object. +// This returns the bytes of the messageID. func (messageMetadata *MessageMetadata) ObjectStorageKey() []byte { - return messageMetadata.messageId.Bytes() + return messageMetadata.messageID.Bytes() } +// ObjectStorageValue returns the value of the stored message metadata object. +// This includes the receivedTime, solidificationTime and solid status. func (messageMetadata *MessageMetadata) ObjectStorageValue() []byte { return marshalutil.New(). WriteTime(messageMetadata.ReceivedTime()). @@ -130,6 +142,7 @@ func (messageMetadata *MessageMetadata) ObjectStorageValue() []byte { Bytes() } +// UnmarshalObjectStorageValue unmarshals the stored bytes into a messageMetadata. func (messageMetadata *MessageMetadata) UnmarshalObjectStorageValue(data []byte) (consumedBytes int, err error) { marshalUtil := marshalutil.New(data) @@ -148,28 +161,34 @@ func (messageMetadata *MessageMetadata) UnmarshalObjectStorageValue(data []byte) return } +// Update updates the message metadata. +// This should never happen and will panic if attempted. func (messageMetadata *MessageMetadata) Update(other objectstorage.StorableObject) { panic("updates disabled") } var _ objectstorage.StorableObject = &MessageMetadata{} +// CachedMessageMetadata is a wrapper for stored cached object that represents a message metadata. type CachedMessageMetadata struct { objectstorage.CachedObject } +// Retain registers a new consumer for the cached message metadata. func (cachedMessageMetadata *CachedMessageMetadata) Retain() *CachedMessageMetadata { return &CachedMessageMetadata{cachedMessageMetadata.CachedObject.Retain()} } +// Unwrap returns the underlying stored message metadata wrapped by the CachedMessageMetadata. +// If the stored object cannot be cast to MessageMetadata or is deleted, it returns nil. func (cachedMessageMetadata *CachedMessageMetadata) Unwrap() *MessageMetadata { - if untypedObject := cachedMessageMetadata.Get(); untypedObject == nil { + untypedObject := cachedMessageMetadata.Get() + if untypedObject == nil { + return nil + } + typedObject := untypedObject.(*MessageMetadata) + if typedObject == nil || typedObject.IsDeleted() { return nil - } else { - if typedObject := untypedObject.(*MessageMetadata); typedObject == nil || typedObject.IsDeleted() { - return nil - } else { - return typedObject - } } + return typedObject } diff --git a/packages/binary/messagelayer/tangle/missingmessage.go b/packages/binary/messagelayer/tangle/missingmessage.go index 1fb9e4b2f01532c77a40b9963c5d0e27502b9861..f8ba9f2983b6433c4b3cd3a749bfa8545fe62187 100644 --- a/packages/binary/messagelayer/tangle/missingmessage.go +++ b/packages/binary/messagelayer/tangle/missingmessage.go @@ -9,20 +9,25 @@ import ( "github.com/iotaledger/goshimmer/packages/binary/messagelayer/message" ) +// MissingMessage represents a missing message. type MissingMessage struct { objectstorage.StorableObjectFlags - messageId message.Id + messageID message.ID missingSince time.Time } -func NewMissingMessage(messageId message.Id) *MissingMessage { +// NewMissingMessage creates new missing message with the specified messageID. +func NewMissingMessage(messageID message.ID) *MissingMessage { return &MissingMessage{ - messageId: messageId, + messageID: messageID, missingSince: time.Now(), } } +// MissingMessageFromStorageKey unmarshals the stored key into a desirable target specified by 0 or 1 optional argument. +// The default target is MissingMessage. +// It unmarshals into the target specified or panics if more than 1 target is specified. func MissingMessageFromStorageKey(key []byte, optionalTargetObject ...*MissingMessage) (result objectstorage.StorableObject, consumedBytes int, err error) { // determine the target object that will hold the unmarshaled information switch len(optionalTargetObject) { @@ -36,7 +41,7 @@ func MissingMessageFromStorageKey(key []byte, optionalTargetObject ...*MissingMe // parse the properties that are stored in the key marshalUtil := marshalutil.New(key) - result.(*MissingMessage).messageId, err = message.ParseId(marshalUtil) + result.(*MissingMessage).messageID, err = message.ParseID(marshalUtil) if err != nil { return } @@ -45,9 +50,9 @@ func MissingMessageFromStorageKey(key []byte, optionalTargetObject ...*MissingMe return } -// MessageId returns the id of the message. -func (missingMessage *MissingMessage) MessageId() message.Id { - return missingMessage.messageId +// MessageID returns the id of the message. +func (missingMessage *MissingMessage) MessageID() message.ID { + return missingMessage.messageID } // MissingSince returns the time since when this message is missing. @@ -55,14 +60,19 @@ func (missingMessage *MissingMessage) MissingSince() time.Time { return missingMessage.missingSince } +// Update update the missing message. +// It should never happen and will panic if called. func (missingMessage *MissingMessage) Update(other objectstorage.StorableObject) { panic("missing messages should never be overwritten and only stored once to optimize IO") } +// ObjectStorageKey returns the key of the stored missing message. +// This returns the bytes of the messageID of the missing message. func (missingMessage *MissingMessage) ObjectStorageKey() []byte { - return missingMessage.messageId[:] + return missingMessage.messageID[:] } +// ObjectStorageValue returns the value of the stored missing message. func (missingMessage *MissingMessage) ObjectStorageValue() (result []byte) { result, err := missingMessage.missingSince.MarshalBinary() if err != nil { @@ -72,6 +82,7 @@ func (missingMessage *MissingMessage) ObjectStorageValue() (result []byte) { return } +// UnmarshalObjectStorageValue unmarshals the stored bytes into a missing message. func (missingMessage *MissingMessage) UnmarshalObjectStorageValue(data []byte) (consumedBytes int, err error) { marshalUtil := marshalutil.New(data) missingMessage.missingSince, err = marshalUtil.ReadTime() diff --git a/packages/binary/messagelayer/tangle/storageprefixes.go b/packages/binary/messagelayer/tangle/storageprefixes.go index 24a31eea08c886d9f649b490c1fa77e444896447..1e3e0ff536b87dc99f9a01d7ac15042999636623 100644 --- a/packages/binary/messagelayer/tangle/storageprefixes.go +++ b/packages/binary/messagelayer/tangle/storageprefixes.go @@ -1,8 +1,12 @@ package tangle const ( + // PrefixMessage defines the storage prefix for message. PrefixMessage byte = iota + // PrefixMessageMetadata defines the storage prefix for message metadata. PrefixMessageMetadata + // PrefixApprovers defines the storage prefix for approvers. PrefixApprovers + // PrefixMissingMessage defines the storage prefix for missing message. PrefixMissingMessage ) diff --git a/packages/binary/messagelayer/tangle/tangle.go b/packages/binary/messagelayer/tangle/tangle.go index 7baf9d64dbd68d53a9111d1a92012b694740513c..29348f0aa7a342da1d4170e8bac25d054e427e44 100644 --- a/packages/binary/messagelayer/tangle/tangle.go +++ b/packages/binary/messagelayer/tangle/tangle.go @@ -50,7 +50,7 @@ func New(store kvstore.KVStore) (result *Tangle) { shutdown: make(chan struct{}), messageStorage: osFactory.New(PrefixMessage, messageFactory, objectstorage.CacheTime(cacheTime), objectstorage.LeakDetectionEnabled(false)), messageMetadataStorage: osFactory.New(PrefixMessageMetadata, MessageMetadataFromStorageKey, objectstorage.CacheTime(cacheTime), objectstorage.LeakDetectionEnabled(false)), - approverStorage: osFactory.New(PrefixApprovers, approverFactory, objectstorage.CacheTime(cacheTime), objectstorage.PartitionKey(message.IdLength, message.IdLength), objectstorage.LeakDetectionEnabled(false)), + approverStorage: osFactory.New(PrefixApprovers, approverFactory, objectstorage.CacheTime(cacheTime), objectstorage.PartitionKey(message.IDLength, message.IDLength), objectstorage.LeakDetectionEnabled(false)), missingMessageStorage: osFactory.New(PrefixMissingMessage, missingMessageFactory, objectstorage.CacheTime(cacheTime), objectstorage.LeakDetectionEnabled(false)), Events: *newEvents(), @@ -67,46 +67,46 @@ func (tangle *Tangle) AttachMessage(msg *message.Message) { } // Message retrieves a message from the tangle. -func (tangle *Tangle) Message(messageId message.Id) *message.CachedMessage { - return &message.CachedMessage{CachedObject: tangle.messageStorage.Load(messageId[:])} +func (tangle *Tangle) Message(messageID message.ID) *message.CachedMessage { + return &message.CachedMessage{CachedObject: tangle.messageStorage.Load(messageID[:])} } // MessageMetadata retrieves the metadata of a message from the tangle. -func (tangle *Tangle) MessageMetadata(messageId message.Id) *CachedMessageMetadata { - return &CachedMessageMetadata{CachedObject: tangle.messageMetadataStorage.Load(messageId[:])} +func (tangle *Tangle) MessageMetadata(messageID message.ID) *CachedMessageMetadata { + return &CachedMessageMetadata{CachedObject: tangle.messageMetadataStorage.Load(messageID[:])} } // Approvers retrieves the approvers of a message from the tangle. -func (tangle *Tangle) Approvers(messageId message.Id) CachedApprovers { +func (tangle *Tangle) Approvers(messageID message.ID) CachedApprovers { approvers := make(CachedApprovers, 0) tangle.approverStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool { approvers = append(approvers, &CachedApprover{CachedObject: cachedObject}) return true - }, messageId[:]) + }, messageID[:]) return approvers } // DeleteMessage deletes a message and its association to approvees by un-marking the given // message as an approver. -func (tangle *Tangle) DeleteMessage(messageId message.Id) { - tangle.Message(messageId).Consume(func(currentMsg *message.Message) { - trunkMsgId := currentMsg.TrunkId() - tangle.deleteApprover(trunkMsgId, messageId) - - branchMsgId := currentMsg.BranchId() - if branchMsgId != trunkMsgId { - tangle.deleteApprover(branchMsgId, messageId) +func (tangle *Tangle) DeleteMessage(messageID message.ID) { + tangle.Message(messageID).Consume(func(currentMsg *message.Message) { + trunkMsgID := currentMsg.TrunkID() + tangle.deleteApprover(trunkMsgID, messageID) + + branchMsgID := currentMsg.BranchID() + if branchMsgID != trunkMsgID { + tangle.deleteApprover(branchMsgID, messageID) } - tangle.messageMetadataStorage.Delete(messageId[:]) - tangle.messageStorage.Delete(messageId[:]) + tangle.messageMetadataStorage.Delete(messageID[:]) + tangle.messageStorage.Delete(messageID[:]) - tangle.Events.MessageRemoved.Trigger(messageId) + tangle.Events.MessageRemoved.Trigger(messageID) }) } // DeleteMissingMessage deletes a message from the missingMessageStorage. -func (tangle *Tangle) DeleteMissingMessage(messageID message.Id) { +func (tangle *Tangle) DeleteMissingMessage(messageID message.ID) { tangle.missingMessageStorage.Delete(messageID[:]) } @@ -170,12 +170,12 @@ func (tangle *Tangle) DBStats() (solidCount int, messageCount int, avgSolidifica } // MissingMessages return the ids of messages in missingMessageStorage -func (tangle *Tangle) MissingMessages() (ids []message.Id) { +func (tangle *Tangle) MissingMessages() (ids []message.ID) { tangle.missingMessageStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool { cachedObject.Consume(func(object objectstorage.StorableObject) { missingMsg := object.(*MissingMessage) if !missingMsg.IsDeleted() { - ids = append(ids, missingMsg.messageId) + ids = append(ids, missingMsg.messageID) } }) return true @@ -194,20 +194,20 @@ func (tangle *Tangle) storeMessageWorker(msg *message.Message) { cachedMessage = &message.CachedMessage{CachedObject: _tmp} // store message metadata - messageId := msg.Id() - cachedMsgMetadata := &CachedMessageMetadata{CachedObject: tangle.messageMetadataStorage.Store(NewMessageMetadata(messageId))} + messageID := msg.ID() + cachedMsgMetadata := &CachedMessageMetadata{CachedObject: tangle.messageMetadataStorage.Store(NewMessageMetadata(messageID))} // store trunk approver - trunkMsgId := msg.TrunkId() - tangle.approverStorage.Store(NewApprover(trunkMsgId, messageId)).Release() + trunkMsgID := msg.TrunkID() + tangle.approverStorage.Store(NewApprover(trunkMsgID, messageID)).Release() // store branch approver - if branchMsgId := msg.BranchId(); branchMsgId != trunkMsgId { - tangle.approverStorage.Store(NewApprover(branchMsgId, messageId)).Release() + if branchMsgID := msg.BranchID(); branchMsgID != trunkMsgID { + tangle.approverStorage.Store(NewApprover(branchMsgID, messageID)).Release() } // trigger events - if tangle.missingMessageStorage.DeleteIfPresent(messageId[:]) { + if tangle.missingMessageStorage.DeleteIfPresent(messageID[:]) { tangle.Events.MissingMessageReceived.Trigger(cachedMessage, cachedMsgMetadata) } @@ -220,21 +220,21 @@ func (tangle *Tangle) storeMessageWorker(msg *message.Message) { } // checks whether the given message is solid and marks it as missing if it isn't known. -func (tangle *Tangle) isMessageMarkedAsSolid(messageId message.Id) bool { - if messageId == message.EmptyId { +func (tangle *Tangle) isMessageMarkedAsSolid(messageID message.ID) bool { + if messageID == message.EmptyID { return true } - msgMetadataCached := tangle.MessageMetadata(messageId) + msgMetadataCached := tangle.MessageMetadata(messageID) defer msgMetadataCached.Release() msgMetadata := msgMetadataCached.Unwrap() // mark message as missing if msgMetadata == nil { - missingMessage := NewMissingMessage(messageId) + missingMessage := NewMissingMessage(messageID) if cachedMissingMessage, stored := tangle.missingMessageStorage.StoreIfAbsent(missingMessage); stored { cachedMissingMessage.Consume(func(object objectstorage.StorableObject) { - tangle.Events.MessageMissing.Trigger(messageId) + tangle.Events.MessageMissing.Trigger(messageID) }) } return false @@ -259,8 +259,8 @@ func (tangle *Tangle) isMessageSolid(msg *message.Message, msgMetadata *MessageM } // as missing messages are requested in isMessageMarkedAsSolid, we want to prevent short-circuit evaluation - trunkSolid := tangle.isMessageMarkedAsSolid(msg.TrunkId()) - branchSolid := tangle.isMessageMarkedAsSolid(msg.BranchId()) + trunkSolid := tangle.isMessageMarkedAsSolid(msg.TrunkID()) + branchSolid := tangle.isMessageMarkedAsSolid(msg.BranchID()) return trunkSolid && branchSolid } @@ -297,11 +297,11 @@ func (tangle *Tangle) checkMessageSolidityAndPropagate(cachedMessage *message.Ca tangle.Events.MessageSolid.Trigger(currentCachedMessage, currentCachedMsgMetadata) // auto. push approvers of the newly solid message to propagate solidification - tangle.Approvers(currentMessage.Id()).Consume(func(approver *Approver) { - approverMessageId := approver.ApproverMessageId() + tangle.Approvers(currentMessage.ID()).Consume(func(approver *Approver) { + approverMessageID := approver.ApproverMessageID() solidificationStack.PushBack([2]interface{}{ - tangle.Message(approverMessageId), - tangle.MessageMetadata(approverMessageId), + tangle.Message(approverMessageID), + tangle.MessageMetadata(approverMessageID), }) }) } @@ -312,33 +312,34 @@ func (tangle *Tangle) checkMessageSolidityAndPropagate(cachedMessage *message.Ca } // deletes the given approver association for the given approvee to its approver. -func (tangle *Tangle) deleteApprover(approvedMessageId message.Id, approvingMessage message.Id) { - idToDelete := make([]byte, message.IdLength+message.IdLength) - copy(idToDelete[:message.IdLength], approvedMessageId[:]) - copy(idToDelete[message.IdLength:], approvingMessage[:]) +func (tangle *Tangle) deleteApprover(approvedMessageID message.ID, approvingMessage message.ID) { + idToDelete := make([]byte, message.IDLength+message.IDLength) + copy(idToDelete[:message.IDLength], approvedMessageID[:]) + copy(idToDelete[message.IDLength:], approvingMessage[:]) tangle.approverStorage.Delete(idToDelete) } // deletes a message and its future cone of messages/approvers. -func (tangle *Tangle) deleteFutureCone(messageId message.Id) { +// nolint +func (tangle *Tangle) deleteFutureCone(messageID message.ID) { cleanupStack := list.New() - cleanupStack.PushBack(messageId) + cleanupStack.PushBack(messageID) - processedMessages := make(map[message.Id]types.Empty) - processedMessages[messageId] = types.Void + processedMessages := make(map[message.ID]types.Empty) + processedMessages[messageID] = types.Void for cleanupStack.Len() >= 1 { currentStackEntry := cleanupStack.Front() - currentMessageId := currentStackEntry.Value.(message.Id) + currentMessageID := currentStackEntry.Value.(message.ID) cleanupStack.Remove(currentStackEntry) - tangle.DeleteMessage(currentMessageId) + tangle.DeleteMessage(currentMessageID) - tangle.Approvers(currentMessageId).Consume(func(approver *Approver) { - approverId := approver.ApproverMessageId() - if _, messageProcessed := processedMessages[approverId]; !messageProcessed { - cleanupStack.PushBack(approverId) - processedMessages[approverId] = types.Void + tangle.Approvers(currentMessageID).Consume(func(approver *Approver) { + approverID := approver.ApproverMessageID() + if _, messageProcessed := processedMessages[approverID]; !messageProcessed { + cleanupStack.PushBack(approverID) + processedMessages[approverID] = types.Void } }) } @@ -357,14 +358,14 @@ func (tangle *Tangle) StoreMessageWorkerPoolStatus() (name string, load int) { // RetrieveAllTips returns the tips (i.e., solid messages that are not part of the approvers list). // It iterates over the messageMetadataStorage, thus only use this method if necessary. // TODO: improve this function. -func (tangle *Tangle) RetrieveAllTips() (tips []message.Id) { +func (tangle *Tangle) RetrieveAllTips() (tips []message.ID) { tangle.messageMetadataStorage.ForEach(func(key []byte, cachedMessage objectstorage.CachedObject) bool { cachedMessage.Consume(func(object objectstorage.StorableObject) { messageMetadata := object.(*MessageMetadata) if messageMetadata != nil && messageMetadata.IsSolid() { - cachedApprovers := tangle.Approvers(messageMetadata.messageId) + cachedApprovers := tangle.Approvers(messageMetadata.messageID) if len(cachedApprovers) == 0 { - tips = append(tips, messageMetadata.messageId) + tips = append(tips, messageMetadata.messageID) } cachedApprovers.Consume(func(approver *Approver) {}) } diff --git a/packages/binary/messagelayer/tangle/tangle_test.go b/packages/binary/messagelayer/tangle/tangle_test.go index f0baac00765c9f5d564c879e98faf8ebcebfd848..44320acd6cbe132b0b1655d7a8d9a61a657ed508 100644 --- a/packages/binary/messagelayer/tangle/tangle_test.go +++ b/packages/binary/messagelayer/tangle/tangle_test.go @@ -47,7 +47,7 @@ func TestTangle_AttachMessage(t *testing.T) { cachedMessageMetadata.Release() cachedMessage.Consume(func(msg *message.Message) { - fmt.Println("ATTACHED:", msg.Id()) + fmt.Println("ATTACHED:", msg.ID()) }) })) @@ -55,19 +55,19 @@ func TestTangle_AttachMessage(t *testing.T) { cachedMessageMetadata.Release() cachedMessage.Consume(func(msg *message.Message) { - fmt.Println("SOLID:", msg.Id()) + fmt.Println("SOLID:", msg.ID()) }) })) - messageTangle.Events.MessageUnsolidifiable.Attach(events.NewClosure(func(messageId message.Id) { + messageTangle.Events.MessageUnsolidifiable.Attach(events.NewClosure(func(messageId message.ID) { fmt.Println("UNSOLIDIFIABLE:", messageId) })) - messageTangle.Events.MessageMissing.Attach(events.NewClosure(func(messageId message.Id) { + messageTangle.Events.MessageMissing.Attach(events.NewClosure(func(messageId message.ID) { fmt.Println("MISSING:", messageId) })) - messageTangle.Events.MessageRemoved.Attach(events.NewClosure(func(messageId message.Id) { + messageTangle.Events.MessageRemoved.Attach(events.NewClosure(func(messageId message.ID) { fmt.Println("REMOVED:", messageId) })) @@ -84,5 +84,5 @@ func TestTangle_AttachMessage(t *testing.T) { } func newTestMessage(payloadString string) *message.Message { - return message.New(message.EmptyId, message.EmptyId, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) + return message.New(message.EmptyID, message.EmptyID, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) } diff --git a/packages/binary/messagelayer/test/data_payload_test.go b/packages/binary/messagelayer/test/data_payload_test.go index 2ee00c524467f158b3d8d6e0984e34bfc3968b7a..b4497fd190cb185197bbbd2b20900a7b43b59fae 100644 --- a/packages/binary/messagelayer/test/data_payload_test.go +++ b/packages/binary/messagelayer/test/data_payload_test.go @@ -22,7 +22,7 @@ func BenchmarkVerifyDataMessages(b *testing.B) { var pool async.WorkerPool pool.Tune(runtime.GOMAXPROCS(0)) - factory := messagefactory.New(mapdb.NewMapDB(), []byte(messagelayer.DBSequenceNumber), identity.GenerateLocalIdentity(), messagefactory.TipSelectorFunc(func() (message.Id, message.Id) { return message.EmptyId, message.EmptyId })) + factory := messagefactory.New(mapdb.NewMapDB(), []byte(messagelayer.DBSequenceNumber), identity.GenerateLocalIdentity(), messagefactory.TipSelectorFunc(func() (message.ID, message.ID) { return message.EmptyID, message.EmptyID })) messages := make([][]byte, b.N) for i := 0; i < b.N; i++ { @@ -36,7 +36,7 @@ func BenchmarkVerifyDataMessages(b *testing.B) { for i := 0; i < b.N; i++ { currentIndex := i pool.Submit(func() { - if msg, err, _ := message.FromBytes(messages[currentIndex]); err != nil { + if msg, _, err := message.FromBytes(messages[currentIndex]); err != nil { b.Error(err) } else { msg.VerifySignature() @@ -50,7 +50,7 @@ func BenchmarkVerifyDataMessages(b *testing.B) { func BenchmarkVerifySignature(b *testing.B) { pool, _ := ants.NewPool(80, ants.WithNonblocking(false)) - factory := messagefactory.New(mapdb.NewMapDB(), []byte(messagelayer.DBSequenceNumber), identity.GenerateLocalIdentity(), messagefactory.TipSelectorFunc(func() (message.Id, message.Id) { return message.EmptyId, message.EmptyId })) + factory := messagefactory.New(mapdb.NewMapDB(), []byte(messagelayer.DBSequenceNumber), identity.GenerateLocalIdentity(), messagefactory.TipSelectorFunc(func() (message.ID, message.ID) { return message.EmptyID, message.EmptyID })) messages := make([]*message.Message, b.N) for i := 0; i < b.N; i++ { diff --git a/packages/binary/messagelayer/test/message_test.go b/packages/binary/messagelayer/test/message_test.go index 99d1e11ca209a1d29d2161e086c882225b4ec52a..585dae549ba31d0d08807f6f93a8828b69fa6731 100644 --- a/packages/binary/messagelayer/test/message_test.go +++ b/packages/binary/messagelayer/test/message_test.go @@ -18,7 +18,7 @@ import ( ) func TestMessage_StorableObjectFromKey(t *testing.T) { - key, err := message.NewId("2DYebCqnZ8PS5PyXBEvAvLB1fCF77Rn9RtofNHjEb2pSTujKi889d31FmguAs5DgL7YURw4GP2Y28JdJ7K4bjudG") + key, err := message.NewID("2DYebCqnZ8PS5PyXBEvAvLB1fCF77Rn9RtofNHjEb2pSTujKi889d31FmguAs5DgL7YURw4GP2Y28JdJ7K4bjudG") if err != nil { panic(err) } @@ -28,21 +28,21 @@ func TestMessage_StorableObjectFromKey(t *testing.T) { panic(err) } - assert.Equal(t, message.IdLength, consumedBytes) - assert.Equal(t, key, messageFromKey.(*message.Message).Id()) + assert.Equal(t, message.IDLength, consumedBytes) + assert.Equal(t, key, messageFromKey.(*message.Message).ID()) } func TestMessage_VerifySignature(t *testing.T) { keyPair := ed25519.GenerateKeyPair() pl := payload.NewData([]byte("test")) - unsigned := message.New(message.EmptyId, message.EmptyId, time.Time{}, keyPair.PublicKey, 0, pl, 0, ed25519.Signature{}) + unsigned := message.New(message.EmptyID, message.EmptyID, time.Time{}, keyPair.PublicKey, 0, pl, 0, ed25519.Signature{}) assert.False(t, unsigned.VerifySignature()) unsignedBytes := unsigned.Bytes() signature := keyPair.PrivateKey.Sign(unsignedBytes[:len(unsignedBytes)-ed25519.SignatureSize]) - signed := message.New(message.EmptyId, message.EmptyId, time.Time{}, keyPair.PublicKey, 0, pl, 0, signature) + signed := message.New(message.EmptyID, message.EmptyID, time.Time{}, keyPair.PublicKey, 0, pl, 0, signature) assert.True(t, signed.VerifySignature()) } @@ -56,11 +56,11 @@ func TestMessage_MarshalUnmarshal(t *testing.T) { t.Log(testMessage) - restoredMessage, err, _ := message.FromBytes(testMessage.Bytes()) + restoredMessage, _, err := message.FromBytes(testMessage.Bytes()) if assert.NoError(t, err, err) { - assert.Equal(t, testMessage.Id(), restoredMessage.Id()) - assert.Equal(t, testMessage.TrunkId(), restoredMessage.TrunkId()) - assert.Equal(t, testMessage.BranchId(), restoredMessage.BranchId()) + assert.Equal(t, testMessage.ID(), restoredMessage.ID()) + assert.Equal(t, testMessage.TrunkID(), restoredMessage.TrunkID()) + assert.Equal(t, testMessage.BranchID(), restoredMessage.BranchID()) assert.Equal(t, testMessage.IssuerPublicKey(), restoredMessage.IssuerPublicKey()) assert.Equal(t, testMessage.IssuingTime().Round(time.Second), restoredMessage.IssuingTime().Round(time.Second)) assert.Equal(t, testMessage.SequenceNumber(), restoredMessage.SequenceNumber()) diff --git a/packages/binary/messagelayer/test/retrievealltips_test.go b/packages/binary/messagelayer/test/retrievealltips_test.go index 7b55bff534f16d53d2655bb41828ada301ab4723..089f222968b62ff78c9db067678c4542c7315359 100644 --- a/packages/binary/messagelayer/test/retrievealltips_test.go +++ b/packages/binary/messagelayer/test/retrievealltips_test.go @@ -17,9 +17,9 @@ import ( func TestRetrieveAllTips(t *testing.T) { messageTangle := tangle.New(mapdb.NewMapDB()) - messageA := newTestMessage("A", message.EmptyId, message.EmptyId) - messageB := newTestMessage("B", messageA.Id(), message.EmptyId) - messageC := newTestMessage("C", messageA.Id(), message.EmptyId) + messageA := newTestMessage("A", message.EmptyID, message.EmptyID) + messageB := newTestMessage("B", messageA.ID(), message.EmptyID) + messageC := newTestMessage("C", messageA.ID(), message.EmptyID) var wg sync.WaitGroup @@ -43,6 +43,6 @@ func TestRetrieveAllTips(t *testing.T) { messageTangle.Shutdown() } -func newTestMessage(payloadString string, parent1, parent2 message.Id) *message.Message { +func newTestMessage(payloadString string, parent1, parent2 message.ID) *message.Message { return message.New(parent1, parent2, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) } diff --git a/packages/binary/messagelayer/tipselector/events.go b/packages/binary/messagelayer/tipselector/events.go index 2e39a68d1d5dd6206f4bdef35bb7eabbcb32bc3c..348985408f3b29b03fba5f06f926b4d779ca06d8 100644 --- a/packages/binary/messagelayer/tipselector/events.go +++ b/packages/binary/messagelayer/tipselector/events.go @@ -14,6 +14,6 @@ type Events struct { TipRemoved *events.Event } -func messageIdEvent(handler interface{}, params ...interface{}) { - handler.(func(message.Id))(params[0].(message.Id)) +func messageIDEvent(handler interface{}, params ...interface{}) { + handler.(func(message.ID))(params[0].(message.ID)) } diff --git a/packages/binary/messagelayer/tipselector/tipselector.go b/packages/binary/messagelayer/tipselector/tipselector.go index aded723b7e7d3b99e1089f3bdc5646c7c278f9cd..f2e62bb7a5a61941154b51950f48055b495e9a0e 100644 --- a/packages/binary/messagelayer/tipselector/tipselector.go +++ b/packages/binary/messagelayer/tipselector/tipselector.go @@ -14,12 +14,12 @@ type TipSelector struct { } // New creates a new tip-selector. -func New(tips ...message.Id) *TipSelector { +func New(tips ...message.ID) *TipSelector { tipSelector := &TipSelector{ tips: datastructure.NewRandomMap(), Events: Events{ - TipAdded: events.NewEvent(messageIdEvent), - TipRemoved: events.NewEvent(messageIdEvent), + TipAdded: events.NewEvent(messageIDEvent), + TipRemoved: events.NewEvent(messageIDEvent), }, } @@ -31,7 +31,7 @@ func New(tips ...message.Id) *TipSelector { } // Set adds the given messageIDs as tips. -func (tipSelector *TipSelector) Set(tips ...message.Id) { +func (tipSelector *TipSelector) Set(tips ...message.ID) { for _, messageID := range tips { tipSelector.tips.Set(messageID, messageID) } @@ -39,42 +39,42 @@ func (tipSelector *TipSelector) Set(tips ...message.Id) { // AddTip adds the given message as a tip. func (tipSelector *TipSelector) AddTip(msg *message.Message) { - messageId := msg.Id() - if tipSelector.tips.Set(messageId, messageId) { - tipSelector.Events.TipAdded.Trigger(messageId) + messageID := msg.ID() + if tipSelector.tips.Set(messageID, messageID) { + tipSelector.Events.TipAdded.Trigger(messageID) } - trunkMessageId := msg.TrunkId() - if _, deleted := tipSelector.tips.Delete(trunkMessageId); deleted { - tipSelector.Events.TipRemoved.Trigger(trunkMessageId) + trunkMessageID := msg.TrunkID() + if _, deleted := tipSelector.tips.Delete(trunkMessageID); deleted { + tipSelector.Events.TipRemoved.Trigger(trunkMessageID) } - branchMessageId := msg.BranchId() - if _, deleted := tipSelector.tips.Delete(branchMessageId); deleted { - tipSelector.Events.TipRemoved.Trigger(branchMessageId) + branchMessageID := msg.BranchID() + if _, deleted := tipSelector.tips.Delete(branchMessageID); deleted { + tipSelector.Events.TipRemoved.Trigger(branchMessageID) } } // Tips returns two tips. -func (tipSelector *TipSelector) Tips() (trunkMessageId, branchMessageId message.Id) { +func (tipSelector *TipSelector) Tips() (trunkMessageID, branchMessageID message.ID) { tip := tipSelector.tips.RandomEntry() if tip == nil { - trunkMessageId = message.EmptyId - branchMessageId = message.EmptyId + trunkMessageID = message.EmptyID + branchMessageID = message.EmptyID return } - branchMessageId = tip.(message.Id) + branchMessageID = tip.(message.ID) if tipSelector.tips.Size() == 1 { - trunkMessageId = branchMessageId + trunkMessageID = branchMessageID return } - trunkMessageId = tipSelector.tips.RandomEntry().(message.Id) - for trunkMessageId == branchMessageId && tipSelector.tips.Size() > 1 { - trunkMessageId = tipSelector.tips.RandomEntry().(message.Id) + trunkMessageID = tipSelector.tips.RandomEntry().(message.ID) + for trunkMessageID == branchMessageID && tipSelector.tips.Size() > 1 { + trunkMessageID = tipSelector.tips.RandomEntry().(message.ID) } return diff --git a/packages/binary/messagelayer/tipselector/tipselector_test.go b/packages/binary/messagelayer/tipselector/tipselector_test.go index fbcf727d4b61b2f56312b052e2f73a468d3e5c18..82182e56c1aa6b3437d6bff72baa2a9bef1b0552 100644 --- a/packages/binary/messagelayer/tipselector/tipselector_test.go +++ b/packages/binary/messagelayer/tipselector/tipselector_test.go @@ -17,8 +17,8 @@ func Test(t *testing.T) { // check if first tips point to genesis trunk1, branch1 := tipSelector.Tips() - assert.Equal(t, message.EmptyId, trunk1) - assert.Equal(t, message.EmptyId, branch1) + assert.Equal(t, message.EmptyID, trunk1) + assert.Equal(t, message.EmptyID, branch1) // create a message and attach it message1 := newTestMessage(trunk1, branch1, "testmessage") @@ -29,11 +29,11 @@ func Test(t *testing.T) { // check if next tips point to our first message trunk2, branch2 := tipSelector.Tips() - assert.Equal(t, message1.Id(), trunk2) - assert.Equal(t, message1.Id(), branch2) + assert.Equal(t, message1.ID(), trunk2) + assert.Equal(t, message1.ID(), branch2) // create a 2nd message and attach it - message2 := newTestMessage(message.EmptyId, message.EmptyId, "testmessage") + message2 := newTestMessage(message.EmptyID, message.EmptyID, "testmessage") tipSelector.AddTip(message2) // check if the tip shows up in the tip count @@ -47,10 +47,10 @@ func Test(t *testing.T) { // check if the tip shows replaces the current tips trunk4, branch4 := tipSelector.Tips() assert.Equal(t, 1, tipSelector.TipCount()) - assert.Equal(t, message3.Id(), trunk4) - assert.Equal(t, message3.Id(), branch4) + assert.Equal(t, message3.ID(), trunk4) + assert.Equal(t, message3.ID(), branch4) } -func newTestMessage(trunk, branch message.Id, payloadString string) *message.Message { +func newTestMessage(trunk, branch message.ID, payloadString string) *message.Message { return message.New(trunk, branch, time.Now(), ed25519.PublicKey{}, 0, payload.NewData([]byte(payloadString)), 0, ed25519.Signature{}) } diff --git a/packages/binary/spammer/spammer.go b/packages/binary/spammer/spammer.go index 5758f898fd70c5f8e72b06dab1ad02d904270f34..259ba8fe0abd2d18e32efae1f2ff2082c554b9e0 100644 --- a/packages/binary/spammer/spammer.go +++ b/packages/binary/spammer/spammer.go @@ -17,7 +17,7 @@ type IssuePayloadFunc = func(payload payload.Payload) (*message.Message, error) type Spammer struct { issuePayloadFunc IssuePayloadFunc - processId int64 + processID int64 shutdownSignal chan types.Empty } @@ -31,12 +31,12 @@ func New(issuePayloadFunc IssuePayloadFunc) *Spammer { // Start starts the spammer to spam with the given messages per time unit. func (spammer *Spammer) Start(rate int, timeUnit time.Duration) { - go spammer.run(rate, timeUnit, atomic.AddInt64(&spammer.processId, 1)) + go spammer.run(rate, timeUnit, atomic.AddInt64(&spammer.processID, 1)) } // Shutdown shuts down the spammer. func (spammer *Spammer) Shutdown() { - atomic.AddInt64(&spammer.processId, 1) + atomic.AddInt64(&spammer.processID, 1) } func (spammer *Spammer) run(rate int, timeUnit time.Duration, processID int64) { @@ -44,7 +44,7 @@ func (spammer *Spammer) run(rate int, timeUnit time.Duration, processID int64) { start := time.Now() for { - if atomic.LoadInt64(&spammer.processId) != processID { + if atomic.LoadInt64(&spammer.processID) != processID { return } diff --git a/packages/binary/storageprefix/storageprefix.go b/packages/binary/storageprefix/storageprefix.go index 28ad9403e71a214a1d956f0eeb8a90e3206c4bc1..f6f6fd620353aa15c6f16bfed53589cfcd232b5d 100644 --- a/packages/binary/storageprefix/storageprefix.go +++ b/packages/binary/storageprefix/storageprefix.go @@ -2,9 +2,12 @@ package storageprefix const ( // the following values are a list of prefixes defined as an enum + // package specific prefixes used for the objectstorage in the corresponding packages + _ byte = iota - // package specific prefixes used for the objectstorage in the corresponding packages + // MessageLayer defines the storage prefix for the message layer MessageLayer + // ValueTransfers defines the storage prefix for value transfer. ValueTransfers ) diff --git a/packages/database/prefix/prefix.go b/packages/database/prefix/prefix.go index ddfbad3bdfd918c73f48fdd7ba33b87b55acab9a..955428b65e49e5190e2f101224c79df889ff41e2 100644 --- a/packages/database/prefix/prefix.go +++ b/packages/database/prefix/prefix.go @@ -1,11 +1,18 @@ package prefix const ( + // DBPrefixApprovers defines the prefix of the approvers db DBPrefixApprovers byte = iota + // DBPrefixTransaction defines the prefix of the transaction db DBPrefixTransaction + // DBPrefixBundle defines the prefix of the bundles db DBPrefixBundle + // DBPrefixTransactionMetadata defines the prefix of the transaction metadata db DBPrefixTransactionMetadata + // DBPrefixAddressTransactions defines the prefix of the address transactions db DBPrefixAddressTransactions + // DBPrefixAutoPeering defines the prefix of the autopeering db. DBPrefixAutoPeering + // DBPrefixHealth defines the prefix of the health db. DBPrefixHealth ) diff --git a/packages/gossip/manager.go b/packages/gossip/manager.go index d6489199ea21567ffa7d2526569bee9c32601926..cc850539adeb46e666257daa2b6cc693025e76d5 100644 --- a/packages/gossip/manager.go +++ b/packages/gossip/manager.go @@ -31,7 +31,7 @@ var ( ) // LoadMessageFunc defines a function that returns the message for the given id. -type LoadMessageFunc func(messageId message.Id) ([]byte, error) +type LoadMessageFunc func(messageId message.ID) ([]byte, error) // The Manager handles the connected neighbors. type Manager struct { @@ -166,8 +166,8 @@ func (m *Manager) DropNeighbor(id identity.ID) error { // RequestMessage requests the message with the given id from the neighbors. // If no peer is provided, all neighbors are queried. -func (m *Manager) RequestMessage(messageId []byte, to ...identity.ID) { - msgReq := &pb.MessageRequest{Id: messageId} +func (m *Manager) RequestMessage(messageID []byte, to ...identity.ID) { + msgReq := &pb.MessageRequest{Id: messageID} m.send(marshal(msgReq), to...) } @@ -317,7 +317,7 @@ func (m *Manager) processMessageRequest(data []byte, nbr *Neighbor) { m.log.Debugw("invalid packet", "err", err) } - msgID, _, err := message.IdFromBytes(packet.GetId()) + msgID, _, err := message.IDFromBytes(packet.GetId()) if err != nil { m.log.Debugw("invalid message id:", "err", err) } diff --git a/packages/gossip/manager_test.go b/packages/gossip/manager_test.go index cef576ddb901ced0eb0b2e9007c54ebb691297fe..5ea5511378fad6daa361a12d13d7e2b8a628ab5d 100644 --- a/packages/gossip/manager_test.go +++ b/packages/gossip/manager_test.go @@ -27,7 +27,7 @@ var ( testMessageData = []byte("testMsg") ) -func loadTestMessage(message.Id) ([]byte, error) { return testMessageData, nil } +func loadTestMessage(message.ID) ([]byte, error) { return testMessageData, nil } func TestClose(t *testing.T) { _, teardown, _ := newMockedManager(t, "A") @@ -336,7 +336,7 @@ func TestMessageRequest(t *testing.T) { // wait for the connections to establish wg.Wait() - id := message.Id{} + id := message.ID{} // mgrA should eventually receive the message mgrA.On("messageReceived", &MessageReceivedEvent{Data: testMessageData, Peer: peerB}).Once() diff --git a/packages/shutdown/order.go b/packages/shutdown/order.go index 25003c92ba91d53476a626109b20ae5d27c9e7af..a6612946ec8e186df18a6561ca31a775bb7d6147 100644 --- a/packages/shutdown/order.go +++ b/packages/shutdown/order.go @@ -1,20 +1,36 @@ package shutdown const ( + // PriorityDatabase defines the shutdown priority for the database. PriorityDatabase = iota + // PriorityFPC defines the shutdown priority for FPC. PriorityFPC + // PriorityTangle defines the shutdown priority for the tangle. PriorityTangle + // PriorityMissingMessagesMonitoring defines the shutdown priority for missing message monitor. PriorityMissingMessagesMonitoring + // PriorityFaucet defines the shutdown priority for the faucet. PriorityFaucet + // PriorityRemoteLog defines the shutdown priority for remote log. PriorityRemoteLog + // PriorityAnalysis defines the shutdown priority for analysis server. PriorityAnalysis + // PriorityPrometheus defines the shutdown priority for prometheus. PriorityPrometheus + // PriorityMetrics defines the shutdown priority for metrics server. PriorityMetrics + // PriorityAutopeering defines the shutdown priority for autopeering. PriorityAutopeering + // PriorityGossip defines the shutdown priority for gossip. PriorityGossip + // PriorityWebAPI defines the shutdown priority for webapi. PriorityWebAPI + // PriorityDashboard defines the shutdown priority for dashboard. PriorityDashboard + // PrioritySynchronization defines the shutdown priority for synchronization. PrioritySynchronization + // PrioritySpammer defines the shutdown priority for spammer. PrioritySpammer + // PriorityBootstrap defines the shutdown priority for bootstrap. PriorityBootstrap ) diff --git a/packages/vote/fpc/fpc.go b/packages/vote/fpc/fpc.go index 62571445f2af56d2f8b3b7a8657ceb97bd56de4f..dc6a525e4c4d57356eee5df99b6befd5abd60557 100644 --- a/packages/vote/fpc/fpc.go +++ b/packages/vote/fpc/fpc.go @@ -14,7 +14,9 @@ import ( ) var ( - ErrVoteAlreadyOngoing = errors.New("a vote is already ongoing for the given ID") + // ErrVoteAlreadyOngoing is returned if a vote is already going on for the given ID. + ErrVoteAlreadyOngoing = errors.New("a vote is already ongoing for the given ID") + // ErrNoOpinionGiversAvailable is returned if a round cannot be performed as no opinion gives are available. ErrNoOpinionGiversAvailable = errors.New("can't perform round as no opinion givers are available") ) @@ -61,6 +63,7 @@ type FPC struct { opinionGiverRng *rand.Rand } +// Vote sets an initial opinion on the vote context and enqueues the vote context. func (f *FPC) Vote(id string, initOpn vote.Opinion) error { f.queueMu.Lock() defer f.queueMu.Unlock() @@ -77,6 +80,8 @@ func (f *FPC) Vote(id string, initOpn vote.Opinion) error { return nil } +// IntermediateOpinion returns the last formed opinion. +// If the vote is not found for the specified ID, it returns with error ErrVotingNotFound. func (f *FPC) IntermediateOpinion(id string) (vote.Opinion, error) { f.ctxsMu.RLock() defer f.ctxsMu.RUnlock() @@ -87,6 +92,7 @@ func (f *FPC) IntermediateOpinion(id string) (vote.Opinion, error) { return voteCtx.LastOpinion(), nil } +// Events returns the events which happen on a vote. func (f *FPC) Events() vote.Events { return f.events } diff --git a/packages/vote/net/server.go b/packages/vote/net/server.go index 97209c509c500011758a414921b971ddf3d69000..e91aba982440201ea5f9fb2bb40b9f58e581ddd4 100644 --- a/packages/vote/net/server.go +++ b/packages/vote/net/server.go @@ -39,6 +39,7 @@ type VoterServer struct { queryReceivedEvent *events.Event } +// Opinion replies the query request with an opinion and triggers the events. func (vs *VoterServer) Opinion(ctx context.Context, req *QueryRequest) (*QueryReply, error) { reply := &QueryReply{ Opinion: make([]int32, len(req.Id)), @@ -66,6 +67,7 @@ func (vs *VoterServer) Opinion(ctx context.Context, req *QueryRequest) (*QueryRe return reply, nil } +// Run starts the voting server. func (vs *VoterServer) Run() error { listener, err := net.Listen("tcp", vs.bindAddr) if err != nil { @@ -76,6 +78,7 @@ func (vs *VoterServer) Run() error { return vs.grpcServer.Serve(listener) } +// Shutdown shutdowns the voting server. func (vs *VoterServer) Shutdown() { vs.grpcServer.GracefulStop() } diff --git a/packages/vote/opinion.go b/packages/vote/opinion.go index 2299e81d1d179a341a0f4e2c41e176cf865f36fa..1ddc84ce31e8a817da7dc74f3784777938f7d7f1 100644 --- a/packages/vote/opinion.go +++ b/packages/vote/opinion.go @@ -35,8 +35,11 @@ type Opinions []Opinion type Opinion byte const ( - Like Opinion = 1 << 0 + // Like defines a Like opinion. + Like Opinion = 1 << 0 + // Dislike defines a Dislike opinion. Dislike Opinion = 1 << 1 + // Unknown defines an unknown opinion. Unknown Opinion = 1 << 2 ) diff --git a/packages/vote/voter.go b/packages/vote/voter.go index a061ca3480033db8637160d1c915a3ef9b68f5bc..dff41570ff7a33e15f21fc3658b60060c8dde068 100644 --- a/packages/vote/voter.go +++ b/packages/vote/voter.go @@ -72,7 +72,7 @@ func OpinionCaller(handler interface{}, params ...interface{}) { handler.(func(ev *OpinionEvent))(params[0].(*OpinionEvent)) } -// RoundStats calls the given handler with a RoundStats. +// RoundStatsCaller calls the given handler with a RoundStats. func RoundStatsCaller(handler interface{}, params ...interface{}) { handler.(func(stats *RoundStats))(params[0].(*RoundStats)) } diff --git a/pluginmgr/core/plugins.go b/pluginmgr/core/plugins.go index 0a1a297f21a23dc635425721638e2fce5a06551a..136ff702504cdaa29e41a8bc4f9e81b9ad6da044 100644 --- a/pluginmgr/core/plugins.go +++ b/pluginmgr/core/plugins.go @@ -24,6 +24,7 @@ import ( "github.com/iotaledger/hive.go/node" ) +// PLUGINS is the list of core plugins. var PLUGINS = node.Plugins( banner.Plugin(), config.Plugin(), diff --git a/pluginmgr/research/plugins.go b/pluginmgr/research/plugins.go index 66e4037f1494e4443988c35e824e20376e4b8ca1..e66c2085978674dc8b1c4982d025b0f8f04d5255 100644 --- a/pluginmgr/research/plugins.go +++ b/pluginmgr/research/plugins.go @@ -10,6 +10,7 @@ import ( "github.com/iotaledger/hive.go/node" ) +// PLUGINS is the list of research plugins. var PLUGINS = node.Plugins( remotelog.Plugin(), analysisserver.Plugin(), diff --git a/pluginmgr/ui/plugins.go b/pluginmgr/ui/plugins.go index e3a2dc1a71c2b565e34b1eb8e9ec545e95872863..7bd487f7a069c4dd0f75c03a7dc52dd4d3df72aa 100644 --- a/pluginmgr/ui/plugins.go +++ b/pluginmgr/ui/plugins.go @@ -5,6 +5,7 @@ import ( "github.com/iotaledger/hive.go/node" ) +// PLUGINS is the list of ui plugins. var PLUGINS = node.Plugins( dashboard.Plugin(), ) diff --git a/pluginmgr/webapi/plugins.go b/pluginmgr/webapi/plugins.go index 3113a03f27ba715bab7484c20bbdfc4036a5aaa6..063d883358470ad29327120e29dc91d87e2540d3 100644 --- a/pluginmgr/webapi/plugins.go +++ b/pluginmgr/webapi/plugins.go @@ -16,6 +16,7 @@ import ( "github.com/iotaledger/hive.go/node" ) +// PLUGINS is the list of webapi plugins. var PLUGINS = node.Plugins( webapi.Plugin(), webauth.Plugin(), diff --git a/plugins/analysis/packet/fpc_heartbeat_test.go b/plugins/analysis/packet/fpc_heartbeat_test.go index 50bd6745282873ee2df531851a8749a3aad3ee93..2ccc465c29882c538970f15ed4d8cd87f29dd472 100644 --- a/plugins/analysis/packet/fpc_heartbeat_test.go +++ b/plugins/analysis/packet/fpc_heartbeat_test.go @@ -43,14 +43,14 @@ func TestFPCHeartbeat(t *testing.T) { packet, err := hb.Bytes() require.NoError(t, err) - hbParsed, err := ParseFPCHeartbeat(packet) + _, err = ParseFPCHeartbeat(packet) require.Error(t, err) hb.Version = banner.AppVersion packet, err = hb.Bytes() require.NoError(t, err) - hbParsed, err = ParseFPCHeartbeat(packet) + hbParsed, err := ParseFPCHeartbeat(packet) require.NoError(t, err) require.Equal(t, hb, hbParsed) diff --git a/plugins/analysis/packet/metric_heartbeat_test.go b/plugins/analysis/packet/metric_heartbeat_test.go index 234241a7c4a3c8d56321b1289bc1241fc6056a25..f3b8cc8262a354320e6351c50f3227d64065bb97 100644 --- a/plugins/analysis/packet/metric_heartbeat_test.go +++ b/plugins/analysis/packet/metric_heartbeat_test.go @@ -42,14 +42,14 @@ func TestMetricHeartbeat(t *testing.T) { packet, err := hb.Bytes() require.NoError(t, err) - hbParsed, err := ParseMetricHeartbeat(packet) + _, err = ParseMetricHeartbeat(packet) require.Error(t, err) hb.Version = banner.AppVersion packet, err = hb.Bytes() require.NoError(t, err) - hbParsed, err = ParseMetricHeartbeat(packet) + hbParsed, err := ParseMetricHeartbeat(packet) require.NoError(t, err) require.Equal(t, hb, hbParsed) diff --git a/plugins/autopeering/autopeering.go b/plugins/autopeering/autopeering.go index 4a1db801b0dc52eb3b39c702646afcc2d6813057..ba730e022742eaac5114ef9b84c3a4e32e2f38cd 100644 --- a/plugins/autopeering/autopeering.go +++ b/plugins/autopeering/autopeering.go @@ -3,7 +3,6 @@ package autopeering import ( "errors" "fmt" - "hash/fnv" "net" "strconv" "strings" @@ -163,15 +162,6 @@ func start(shutdownSignal <-chan struct{}) { lPeer.Database().Close() } -func hash32(b []byte) uint32 { - hash := fnv.New32() - _, err := hash.Write(b) - if err != nil { - panic(err) - } - return hash.Sum32() -} - func parseEntryNodes() (result []*peer.Peer, err error) { for _, entryNodeDefinition := range config.Node().GetStringSlice(CfgEntryNodes) { if entryNodeDefinition == "" { diff --git a/plugins/dashboard/explorer_routes.go b/plugins/dashboard/explorer_routes.go index cc5cab1715c709e25941b2194d785cd51d91c820..263bd501d3c8958b84cea77f79d1cd13268e3514 100644 --- a/plugins/dashboard/explorer_routes.go +++ b/plugins/dashboard/explorer_routes.go @@ -41,7 +41,7 @@ type ExplorerMessage struct { } func createExplorerMessage(msg *message.Message) (*ExplorerMessage, error) { - messageID := msg.Id() + messageID := msg.ID() cachedMessageMetadata := messagelayer.Tangle().MessageMetadata(messageID) defer cachedMessageMetadata.Release() messageMetadata := cachedMessageMetadata.Unwrap() @@ -52,8 +52,8 @@ func createExplorerMessage(msg *message.Message) (*ExplorerMessage, error) { IssuerPublicKey: msg.IssuerPublicKey().String(), Signature: msg.Signature().String(), SequenceNumber: msg.SequenceNumber(), - TrunkMessageID: msg.TrunkId().String(), - BranchMessageID: msg.BranchId().String(), + TrunkMessageID: msg.TrunkID().String(), + BranchMessageID: msg.BranchID().String(), Solid: cachedMessageMetadata.Unwrap().IsSolid(), PayloadType: msg.Payload().Type(), Payload: ProcessPayload(msg.Payload()), @@ -87,7 +87,7 @@ type SearchResult struct { func setupExplorerRoutes(routeGroup *echo.Group) { routeGroup.GET("/message/:id", func(c echo.Context) (err error) { - messageID, err := message.NewId(c.Param("id")) + messageID, err := message.NewID(c.Param("id")) if err != nil { return } @@ -125,8 +125,8 @@ func setupExplorerRoutes(routeGroup *echo.Group) { result.Address = addr } - case message.IdLength: - messageID, err := message.NewId(search) + case message.IDLength: + messageID, err := message.NewID(search) if err != nil { return fmt.Errorf("%w: search ID %s", ErrInvalidParameter, search) } @@ -144,7 +144,7 @@ func setupExplorerRoutes(routeGroup *echo.Group) { }) } -func findMessage(messageID message.Id) (explorerMsg *ExplorerMessage, err error) { +func findMessage(messageID message.ID) (explorerMsg *ExplorerMessage, err error) { if !messagelayer.Tangle().Message(messageID).Consume(func(msg *message.Message) { explorerMsg, err = createExplorerMessage(msg) }) { diff --git a/plugins/dashboard/faucet_routes.go b/plugins/dashboard/faucet_routes.go index a545fc0d5dd0989f1b9689b9b4acb88ca5c8f7d6..d566a8083b92cf5bda713e8be155fbfd6d5e8341 100644 --- a/plugins/dashboard/faucet_routes.go +++ b/plugins/dashboard/faucet_routes.go @@ -50,7 +50,7 @@ func sendFaucetReq(addr address.Address) (res *ReqMsg, err error) { } r := &ReqMsg{ - ID: msg.Id().String(), + ID: msg.ID().String(), } return r, nil } diff --git a/plugins/dashboard/livefeed.go b/plugins/dashboard/livefeed.go index 716934ec20c68fe4be304ff9e246fdd042499060..0d3721dad9c347c27e3efda918cfe80515106048 100644 --- a/plugins/dashboard/livefeed.go +++ b/plugins/dashboard/livefeed.go @@ -19,7 +19,7 @@ var liveFeedWorkerPool *workerpool.WorkerPool func configureLiveFeed() { liveFeedWorkerPool = workerpool.New(func(task workerpool.Task) { task.Param(0).(*message.CachedMessage).Consume(func(message *message.Message) { - broadcastWsMessage(&wsmsg{MsgTypeMessage, &msg{message.Id().String(), 0}}) + broadcastWsMessage(&wsmsg{MsgTypeMessage, &msg{message.ID().String(), 0}}) }) task.Return(nil) diff --git a/plugins/dashboard/payload_handler.go b/plugins/dashboard/payload_handler.go index 95c8d19d15da9ca41ca6b39a9edfeb6dd14b471f..462aadaa9132a6d1477db92b28cd1f8534d1ca7d 100644 --- a/plugins/dashboard/payload_handler.go +++ b/plugins/dashboard/payload_handler.go @@ -7,7 +7,7 @@ import ( valuepayload "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/payload" drngpayload "github.com/iotaledger/goshimmer/packages/binary/drng/payload" drngheader "github.com/iotaledger/goshimmer/packages/binary/drng/payload/header" - cb "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + cb "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/goshimmer/packages/binary/messagelayer/payload" syncbeaconpayload "github.com/iotaledger/goshimmer/plugins/syncbeacon/payload" "github.com/iotaledger/hive.go/marshalutil" @@ -31,7 +31,7 @@ type SyncBeaconPayload struct { SentTime int64 `json:"sent_time"` } -// DrngPayload contains the subtype of drng payload, instance Id +// DrngPayload contains the subtype of drng payload, instance ID // and the subpayload type DrngPayload struct { SubPayloadType byte `json:"subpayload_type"` diff --git a/plugins/dashboard/visualizer.go b/plugins/dashboard/visualizer.go index 7ffdd8667a48ddae7d6843213723d354060776b0..42a4a961189ec68bd9dcdda430316edb4d3f3173 100644 --- a/plugins/dashboard/visualizer.go +++ b/plugins/dashboard/visualizer.go @@ -36,7 +36,7 @@ func configureVisualizer() { switch x := task.Param(0).(type) { case *message.CachedMessage: sendVertex(x, task.Param(1).(*tangle.CachedMessageMetadata)) - case message.Id: + case message.ID: sendTipInfo(x, task.Param(1).(bool)) } @@ -53,14 +53,14 @@ func sendVertex(cachedMessage *message.CachedMessage, cachedMessageMetadata *tan return } broadcastWsMessage(&wsmsg{MsgTypeVertex, &vertex{ - ID: msg.Id().String(), - TrunkID: msg.TrunkId().String(), - BranchID: msg.BranchId().String(), + ID: msg.ID().String(), + TrunkID: msg.TrunkID().String(), + BranchID: msg.BranchID().String(), IsSolid: cachedMessageMetadata.Unwrap().IsSolid(), }}, true) } -func sendTipInfo(messageID message.Id, isTip bool) { +func sendTipInfo(messageID message.ID, isTip bool) { broadcastWsMessage(&wsmsg{MsgTypeTipInfo, &tipinfo{ ID: messageID.String(), IsTip: isTip, @@ -78,11 +78,11 @@ func runVisualizer() { } }) - notifyNewTip := events.NewClosure(func(messageId message.Id) { + notifyNewTip := events.NewClosure(func(messageId message.ID) { visualizerWorkerPool.TrySubmit(messageId, true) }) - notifyDeletedTip := events.NewClosure(func(messageId message.Id) { + notifyDeletedTip := events.NewClosure(func(messageId message.ID) { visualizerWorkerPool.TrySubmit(messageId, false) }) diff --git a/plugins/drng/drng.go b/plugins/drng/drng.go index 6bfebe7c3486544bf9eeef52a1759046d7a71898..1ece9d404a32b536a68cc8eb8f7005f6cbe4b5a5 100644 --- a/plugins/drng/drng.go +++ b/plugins/drng/drng.go @@ -7,7 +7,7 @@ import ( "github.com/iotaledger/goshimmer/packages/binary/drng" "github.com/iotaledger/goshimmer/packages/binary/drng/state" - cbPayload "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + cbPayload "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/goshimmer/plugins/config" "github.com/iotaledger/hive.go/crypto/ed25519" "github.com/iotaledger/hive.go/logger" diff --git a/plugins/gossip/gossip.go b/plugins/gossip/gossip.go index 8db0d74ff607b7cdfa1d6a5c245c45b1c01dcf0d..416acde34dffdfa405e32b5f789930039c4b28b6 100644 --- a/plugins/gossip/gossip.go +++ b/plugins/gossip/gossip.go @@ -91,7 +91,7 @@ func start(shutdownSignal <-chan struct{}) { } // loads the given message from the message layer and returns it or an error if not found. -func loadMessage(msgID message.Id) ([]byte, error) { +func loadMessage(msgID message.ID) ([]byte, error) { cachedMessage := messagelayer.Tangle().Message(msgID) defer cachedMessage.Release() if !cachedMessage.Exists() { diff --git a/plugins/gossip/plugin.go b/plugins/gossip/plugin.go index b1b559338379ac1425e68c298b5b00fa48d9a0f0..38ff2ce33b7d0dfc44a9d2ad18354ad7a0908dae 100644 --- a/plugins/gossip/plugin.go +++ b/plugins/gossip/plugin.go @@ -143,7 +143,7 @@ func configureMessageLayer() { })) // request missing messages - messagelayer.MessageRequester().Events.SendRequest.Attach(events.NewClosure(func(msgID message.Id) { + messagelayer.MessageRequester().Events.SendRequest.Attach(events.NewClosure(func(msgID message.ID) { mgr.RequestMessage(msgID[:]) })) } diff --git a/plugins/gossip/tips_broadcaster.go b/plugins/gossip/tips_broadcaster.go index caff47df0e984f1ee31c2145f98465ed8052127e..fb93099852f083f73ccd27562e9f7a027ef29ef4 100644 --- a/plugins/gossip/tips_broadcaster.go +++ b/plugins/gossip/tips_broadcaster.go @@ -15,17 +15,17 @@ const ( tipsBroadcasterName = PluginName + "[TipsBroadcaster]" ) -var tips = tiplist{dict: make(map[message.Id]*list.Element)} +var tips = tiplist{dict: make(map[message.ID]*list.Element)} type tiplist struct { mu sync.Mutex - dict map[message.Id]*list.Element + dict map[message.ID]*list.Element list list.List iterator *list.Element } -func (s *tiplist) AddTip(id message.Id) { +func (s *tiplist) AddTip(id message.ID) { s.mu.Lock() defer s.mu.Unlock() @@ -39,7 +39,7 @@ func (s *tiplist) AddTip(id message.Id) { } } -func (s *tiplist) RemoveTip(id message.Id) { +func (s *tiplist) RemoveTip(id message.ID) { s.mu.Lock() defer s.mu.Unlock() @@ -54,14 +54,14 @@ func (s *tiplist) RemoveTip(id message.Id) { } } -func (s *tiplist) Next() message.Id { +func (s *tiplist) Next() message.ID { s.mu.Lock() defer s.mu.Unlock() if s.iterator == nil { - return message.EmptyId + return message.EmptyID } - id := s.iterator.Value.(message.Id) + id := s.iterator.Value.(message.ID) s.next(s.iterator) return id } @@ -94,14 +94,14 @@ func startTipBroadcaster(shutdownSignal <-chan struct{}) { // broadcasts the next oldest tip from the tip pool to all connected neighbors. func broadcastNextOldestTip() { msgID := tips.Next() - if msgID == message.EmptyId { + if msgID == message.EmptyID { return } broadcastMessage(msgID) } // broadcasts the given message to all neighbors if it exists. -func broadcastMessage(msgID message.Id) { +func broadcastMessage(msgID message.ID) { msgBytes, err := loadMessage(msgID) if err != nil { return diff --git a/plugins/messagelayer/plugin.go b/plugins/messagelayer/plugin.go index 464e38e4662be277d7bdc5322d2550cb170d09b2..2c62b30873cd26e2e92343a31f6ce235bf9a87ba 100644 --- a/plugins/messagelayer/plugin.go +++ b/plugins/messagelayer/plugin.go @@ -20,7 +20,9 @@ import ( ) const ( - PluginName = "MessageLayer" + // PluginName defines the plugin name. + PluginName = "MessageLayer" + // DBSequenceNumber defines the db sequence number. DBSequenceNumber = "seq" ) @@ -118,7 +120,7 @@ func configure(*node.Plugin) { _tangle.Events.MissingMessageReceived.Attach(events.NewClosure(func(cachedMessage *message.CachedMessage, cachedMessageMetadata *tangle.CachedMessageMetadata) { cachedMessageMetadata.Release() cachedMessage.Consume(func(msg *message.Message) { - messageRequester.StopRequest(msg.Id()) + messageRequester.StopRequest(msg.ID()) }) })) @@ -128,7 +130,7 @@ func configure(*node.Plugin) { cachedMessage.Consume(tipSelector.AddTip) })) - MessageRequester().Events.MissingMessageAppeared.Attach(events.NewClosure(func(id message.Id) { + MessageRequester().Events.MissingMessageAppeared.Attach(events.NewClosure(func(id message.ID) { _tangle.DeleteMissingMessage(id) })) } @@ -144,7 +146,7 @@ func run(*node.Plugin) { } // messageExists tells if a given message is present in the node -func messageExists(msgID message.Id) bool { +func messageExists(msgID message.ID) bool { cachedMessage := Tangle().Message(msgID) defer cachedMessage.Release() return cachedMessage.Exists() diff --git a/plugins/metrics/plugin.go b/plugins/metrics/plugin.go index 3166edc6ef40de85bb4d4a4cae0a7c27310849c2..8787745eac6a9e255fe1bd405b8df6d1dfe106c7 100644 --- a/plugins/metrics/plugin.go +++ b/plugins/metrics/plugin.go @@ -103,7 +103,7 @@ func registerLocalMetrics() { })) - messagelayer.Tangle().Events.MessageRemoved.Attach(events.NewClosure(func(messageId message.Id) { + messagelayer.Tangle().Events.MessageRemoved.Attach(events.NewClosure(func(messageId message.ID) { // MessageRemoved triggered when the message gets removed from database. messageTotalCountDB.Dec() })) @@ -124,7 +124,7 @@ func registerLocalMetrics() { })) // fired when a message gets added to missing message storage - messagelayer.Tangle().Events.MessageMissing.Attach(events.NewClosure(func(messageId message.Id) { + messagelayer.Tangle().Events.MessageMissing.Attach(events.NewClosure(func(messageId message.ID) { missingMessageCountDB.Inc() })) diff --git a/plugins/syncbeacon/payload/payload.go b/plugins/syncbeacon/payload/payload.go index 297e20635851c83c6faf782c7d0703138b0d7262..8f4731f3ba7fc206fa2264e72ed04aad1e8f9102 100644 --- a/plugins/syncbeacon/payload/payload.go +++ b/plugins/syncbeacon/payload/payload.go @@ -30,7 +30,7 @@ func NewSyncBeaconPayload(sentTime int64) *Payload { // FromBytes parses the marshaled version of a Payload into an object. // It either returns a new Payload or fills an optionally provided Payload with the parsed information. -func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, err error, consumedBytes int) { +func FromBytes(bytes []byte, optionalTargetObject ...*Payload) (result *Payload, consumedBytes int, err error) { // determine the target object that will hold the unmarshaled information switch len(optionalTargetObject) { case 0: @@ -91,7 +91,7 @@ func (p *Payload) Bytes() []byte { // Unmarshal unmarshals a given slice of bytes and fills the object. func (p *Payload) Unmarshal(data []byte) (err error) { - _, err, _ = FromBytes(data, p) + _, _, err = FromBytes(data, p) return } diff --git a/plugins/syncbeacon/payload/payload_test.go b/plugins/syncbeacon/payload/payload_test.go index 15368166455e8bb5ebc2bd26256b8bc822b69775..085ec72a99310070294c2eb10750cf4b9f74aa83 100644 --- a/plugins/syncbeacon/payload/payload_test.go +++ b/plugins/syncbeacon/payload/payload_test.go @@ -9,14 +9,14 @@ import ( func TestPayload(t *testing.T) { originalPayload := NewSyncBeaconPayload(time.Now().UnixNano()) - clonedPayload1, err, _ := FromBytes(originalPayload.Bytes()) + clonedPayload1, _, err := FromBytes(originalPayload.Bytes()) if err != nil { panic(err) } assert.Equal(t, originalPayload.SentTime(), clonedPayload1.SentTime()) - clonedPayload2, err, _ := FromBytes(clonedPayload1.Bytes()) + clonedPayload2, _, err := FromBytes(clonedPayload1.Bytes()) if err != nil { panic(err) } diff --git a/plugins/syncbeacon/plugin.go b/plugins/syncbeacon/plugin.go index 3461ff403d68a6842f48b70a8e411e394963efd8..0b1e6e1318a863eb6dd053f4f637b7ed7b88590f 100644 --- a/plugins/syncbeacon/plugin.go +++ b/plugins/syncbeacon/plugin.go @@ -73,7 +73,7 @@ func broadcastSyncBeaconPayload() { return } - log.Debugf("issued sync beacon %s", msg.Id()) + log.Debugf("issued sync beacon %s", msg.ID()) } func run(_ *node.Plugin) { diff --git a/plugins/syncbeaconfollower/plugin.go b/plugins/syncbeaconfollower/plugin.go index 3aa3a9e43aa8468ea361f7700b80d2997a735847..69e88877ba0933fce7e129a5680979555ec47b80 100644 --- a/plugins/syncbeaconfollower/plugin.go +++ b/plugins/syncbeaconfollower/plugin.go @@ -43,7 +43,7 @@ const ( // Status represents the status of a beacon node consisting of latest messageID, sentTime and sync status. type Status struct { - MsgID message.Id + MsgID message.ID SentTime int64 Synced bool } @@ -156,7 +156,7 @@ func configure(_ *node.Plugin) { continue } currentBeacons[pubKey] = &Status{ - MsgID: message.EmptyId, + MsgID: message.EmptyID, Synced: false, SentTime: 0, } @@ -193,7 +193,7 @@ func configure(_ *node.Plugin) { } mutex.RUnlock() - handlePayload(payload, msg.IssuerPublicKey(), msg.Id()) + handlePayload(payload, msg.IssuerPublicKey(), msg.ID()) }) })) } @@ -201,7 +201,7 @@ func configure(_ *node.Plugin) { // handlePayload handles the received payload. It does the following checks: // The time that payload was sent is not greater than CfgSyncBeaconMaxTimeWindowSec. If the duration is longer than CfgSyncBeaconMaxTimeWindowSec, we consider that beacon to be out of sync till we receive a newer payload. // More than syncPercentage of followed nodes are also synced, the node is set to synced. Otherwise, its set as desynced. -func handlePayload(syncBeaconPayload *syncbeacon_payload.Payload, issuerPublicKey ed25519.PublicKey, msgID message.Id) { +func handlePayload(syncBeaconPayload *syncbeacon_payload.Payload, issuerPublicKey ed25519.PublicKey, msgID message.ID) { synced := true dur := time.Since(time.Unix(0, syncBeaconPayload.SentTime())) if dur.Seconds() > beaconMaxTimeWindowSec { @@ -240,7 +240,7 @@ func cleanupFollowNodes() { mutex.Lock() defer mutex.Unlock() for publicKey, status := range currentBeacons { - if status.MsgID != message.EmptyId { + if status.MsgID != message.EmptyID { dur := time.Since(time.Unix(0, status.SentTime)) if dur.Seconds() > beaconMaxTimeOfflineSec { currentBeacons[publicKey].Synced = false diff --git a/plugins/webapi/data/plugin.go b/plugins/webapi/data/plugin.go index 04258ba7497706d48811f6c29a1d1ae0a7b9825e..07696d65619fa895f85ad8be19562d10cfff8a14 100644 --- a/plugins/webapi/data/plugin.go +++ b/plugins/webapi/data/plugin.go @@ -48,7 +48,7 @@ func broadcastData(c echo.Context) error { if err != nil { return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } - return c.JSON(http.StatusOK, Response{ID: msg.Id().String()}) + return c.JSON(http.StatusOK, Response{ID: msg.ID().String()}) } // Response contains the ID of the message sent. diff --git a/plugins/webapi/drng/collectivebeacon/handler.go b/plugins/webapi/drng/collectivebeacon/handler.go index 3c21953c861e2b7ef011a772633d2b601a615b2b..9e11d3f0cc423607a414490d47b1fbf7fdc460c5 100644 --- a/plugins/webapi/drng/collectivebeacon/handler.go +++ b/plugins/webapi/drng/collectivebeacon/handler.go @@ -3,7 +3,7 @@ package collectivebeacon import ( "net/http" - "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectiveBeacon/payload" + "github.com/iotaledger/goshimmer/packages/binary/drng/subtypes/collectivebeacon/payload" "github.com/iotaledger/goshimmer/plugins/issuer" "github.com/iotaledger/hive.go/marshalutil" "github.com/labstack/echo" @@ -28,7 +28,7 @@ func Handler(c echo.Context) error { if err != nil { return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) } - return c.JSON(http.StatusOK, Response{ID: msg.Id().String()}) + return c.JSON(http.StatusOK, Response{ID: msg.ID().String()}) } // Response is the HTTP response from broadcasting a collective beacon message. diff --git a/plugins/webapi/faucet/plugin.go b/plugins/webapi/faucet/plugin.go index 0000eb64fd134d006c232a7e94fbf139567cd9d3..7393eb40c1938434035ef2be87118cb2693e1580 100644 --- a/plugins/webapi/faucet/plugin.go +++ b/plugins/webapi/faucet/plugin.go @@ -70,7 +70,7 @@ func requestFunds(c echo.Context) error { return c.JSON(http.StatusInternalServerError, Response{Error: fmt.Sprintf("Failed to send faucetrequest: %s", err.Error())}) } - return c.JSON(http.StatusOK, Response{ID: msg.Id().String()}) + return c.JSON(http.StatusOK, Response{ID: msg.ID().String()}) } // Response contains the ID of the message sent. diff --git a/plugins/webapi/message/plugin.go b/plugins/webapi/message/plugin.go index c65b6c3e4409e2c15bc6d427896552157b25773b..f8742ff66c6aa842cb1f0ff0d0b610a7c7ef729f 100644 --- a/plugins/webapi/message/plugin.go +++ b/plugins/webapi/message/plugin.go @@ -52,7 +52,7 @@ func findMessageByID(c echo.Context) error { for _, id := range request.IDs { log.Info("Received:", id) - msgID, err := message.NewId(id) + msgID, err := message.NewID(id) if err != nil { log.Info(err) return c.JSON(http.StatusBadRequest, Response{Error: err.Error()}) @@ -74,9 +74,9 @@ func findMessageByID(c echo.Context) error { Solid: msgMetadata.IsSolid(), SolidificationTime: msgMetadata.SolidificationTime().Unix(), }, - ID: msg.Id().String(), - TrunkID: msg.TrunkId().String(), - BranchID: msg.BranchId().String(), + ID: msg.ID().String(), + TrunkID: msg.TrunkID().String(), + BranchID: msg.BranchID().String(), IssuerPublicKey: msg.IssuerPublicKey().String(), IssuingTime: msg.IssuingTime().Unix(), SequenceNumber: msg.SequenceNumber(), diff --git a/plugins/webapi/message/sendPayload.go b/plugins/webapi/message/sendPayload.go index cffc572be8a36141ec6f2086edcb1d1d4ec26a3d..6dd31009efff57035826e29853a590b04c5c3dd0 100644 --- a/plugins/webapi/message/sendPayload.go +++ b/plugins/webapi/message/sendPayload.go @@ -27,7 +27,7 @@ func sendPayload(c echo.Context) error { return c.JSON(http.StatusBadRequest, MsgResponse{Error: err.Error()}) } - return c.JSON(http.StatusOK, MsgResponse{ID: msg.Id().String()}) + return c.JSON(http.StatusOK, MsgResponse{ID: msg.ID().String()}) } // MsgResponse contains the ID of the message sent. diff --git a/plugins/webapi/tools/plugin.go b/plugins/webapi/tools/plugin.go index 01be7ca29db944227e748b9d07d5878ac08fc36d..e4b26ca660e9396bddd661d49af58a50997d2cf7 100644 --- a/plugins/webapi/tools/plugin.go +++ b/plugins/webapi/tools/plugin.go @@ -48,7 +48,7 @@ func pastCone(c echo.Context) error { log.Info("Received:", request.ID) - msgID, err := message.NewId(request.ID) + msgID, err := message.NewID(request.ID) if err != nil { log.Info(err) return c.JSON(http.StatusBadRequest, PastConeResponse{Error: err.Error()}) @@ -59,14 +59,14 @@ func pastCone(c echo.Context) error { stack.PushBack(msgID) // keep track of submitted checks (to not re-add something to the stack that is already in it) // searching in double-linked list is quite expensive, but not in a map - submitted := make(map[message.Id]bool) + submitted := make(map[message.ID]bool) // process messages in stack, try to request parents until we end up at the genesis for stack.Len() > 0 { checkedMessageCount++ // pop the first element from stack currentMsgElement := stack.Front() - currentMsgID := currentMsgElement.Value.(message.Id) + currentMsgID := currentMsgElement.Value.(message.ID) stack.Remove(currentMsgElement) // ask node if it has it @@ -79,22 +79,22 @@ func pastCone(c echo.Context) error { // get trunk and branch msg := msgObject.Unwrap() - branchID := msg.BranchId() - trunkID := msg.TrunkId() + branchID := msg.BranchID() + trunkID := msg.TrunkID() // release objects msgObject.Release() msgMetadataObject.Release() - if branchID == message.EmptyId && msg.TrunkId() == message.EmptyId { + if branchID == message.EmptyID && msg.TrunkID() == message.EmptyID { // msg only attaches to genesis continue } else { - if !submitted[branchID] && branchID != message.EmptyId { + if !submitted[branchID] && branchID != message.EmptyID { stack.PushBack(branchID) submitted[branchID] = true } - if !submitted[trunkID] && trunkID != message.EmptyId { + if !submitted[trunkID] && trunkID != message.EmptyID { stack.PushBack(trunkID) submitted[trunkID] = true }