Merge branch 'main' into dependabot/go_modules/lib/github.com/hashicorp/go-getter-1.7.4

This commit is contained in:
Jürgen Eckel 2024-06-25 22:42:19 +02:00
commit 31bf8cc8e8
No known key found for this signature in database
40 changed files with 586 additions and 625 deletions

View File

@ -996,4 +996,7 @@ func (app *App) setupUpgradeHandlers() {
fromVM[machinemoduletypes.ModuleName] = machinemodule.AppModule{}.ConsensusVersion()
return app.mm.RunMigrations(ctx, app.configurator, fromVM)
})
app.UpgradeKeeper.SetUpgradeHandler("v0.10.0", func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) {
return app.mm.RunMigrations(ctx, app.configurator, fromVM)
})
}

View File

@ -16,13 +16,18 @@ import (
var ClaimServiceClient IRCClient
func init() {
func lazyLoad() IRCClient {
if ClaimServiceClient != nil {
return ClaimServiceClient
}
cfg := config.GetConfig()
ClaimServiceClient = NewRCClient(cfg.ClaimHost, &http.Client{})
return ClaimServiceClient
}
func PostClaim(ctx context.Context, beneficiary string, amount uint64, id uint64) (txID string, err error) {
res, err := ClaimServiceClient.PostClaim(ctx, PostClaimRequest{Beneficiary: beneficiary, Amount: amount, ClaimID: int(id)})
client := lazyLoad()
res, err := client.PostClaim(ctx, PostClaimRequest{Beneficiary: beneficiary, Amount: amount, ClaimID: int(id)})
if err != nil {
return
}

View File

@ -66,7 +66,7 @@ func DefaultConfig() *Config {
MqttPort: 1886,
MqttUser: "user",
MqttPassword: "password",
ClaimHost: "testnet-p2r.rddl.io",
ClaimHost: "https://testnet-p2r.rddl.io",
MqttTLS: true,
}
}

View File

@ -46437,7 +46437,7 @@ paths:
}
tags:
- Query
/planetmint/asset/address/{address}/{lookupPeriodInMin}:
/planetmint/asset/address/{address}/{numElements}:
get:
summary: Queries a list of GetCIDsByAddress items.
operationId: PlanetmintgoAssetGetCIDsByAddress
@ -46502,7 +46502,7 @@ paths:
in: path
required: true
type: string
- name: lookupPeriodInMin
- name: numElements
in: path
required: true
type: string

1
go.mod
View File

@ -25,6 +25,7 @@ require (
github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2
github.com/planetmint/planetmint-go/lib v0.5.0
github.com/rddl-network/elements-rpc v1.0.0
github.com/rddl-network/go-utils v0.1.1
github.com/spf13/cast v1.6.0
github.com/spf13/cobra v1.6.1
github.com/spf13/pflag v1.0.5

2
go.sum
View File

@ -892,6 +892,8 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rddl-network/elements-rpc v1.0.0 h1:geFcsaD1t2ONxRC13semPpiOwsJl0ZCfkFT9UIKPZFk=
github.com/rddl-network/elements-rpc v1.0.0/go.mod h1:E35cJMXZqe1iEo/AvjwSWn25mHZ4+y4gV8qj0lWle5c=
github.com/rddl-network/go-utils v0.1.1 h1:41ZrDMM2ree7/OfhKYK4j/SQnyVvms4YirTKneibeyk=
github.com/rddl-network/go-utils v0.1.1/go.mod h1:xKO/ZSAEHwcYe8bNUZjcQCIX+6OMXzEXu1WQ1HqXqZA=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=

View File

@ -3,6 +3,7 @@ package monitor
import (
"encoding/json"
"log"
"strconv"
"time"
"github.com/syndtr/goleveldb/leveldb/iterator"
@ -21,32 +22,31 @@ func (mms *MqttMonitor) AddParticipant(address string, lastSeenTS int64) (err er
lastSeenBytes, err := json.Marshal(lastSeen)
if err != nil {
mms.Log("[Monitor] Error serializing ConversionRequest: " + err.Error())
log.Println("[app] [Monitor] Error serializing ConversionRequest: " + err.Error())
return
}
increaseCounter := false
// returns an error if the entry does not exist (we have to increase the counter in this case)
_, err = mms.db.Get([]byte(address), nil)
if err != nil {
increaseCounter = true
mms.setNumDBElements(mms.getNumDBElements() + 1)
}
mms.dbMutex.Lock()
if increaseCounter {
mms.numberOfElements++
}
err = mms.db.Put([]byte(address), lastSeenBytes, nil)
mms.dbMutex.Unlock()
if err != nil {
log.Println("[Monitor] storing addresses in DB: " + err.Error())
return
log.Println("[app] [Monitor] error storing addresses in DB: " + err.Error())
} else {
log.Println("[app] [Monitor] stored address in DB: " + address)
}
return
}
func (mms *MqttMonitor) deleteEntry(key []byte) (err error) {
mms.setNumDBElements(mms.getNumDBElements() - 1)
mms.dbMutex.Lock()
err = mms.db.Delete(key, nil)
mms.numberOfElements--
mms.dbMutex.Unlock()
return
}
@ -61,8 +61,11 @@ func (mms *MqttMonitor) getAmountOfElements() (amount int64, err error) {
// Check for any errors encountered during iteration
if err := iter.Error(); err != nil {
log.Println("[Monitor] " + err.Error())
log.Println("[app] [Monitor] " + err.Error())
} else {
log.Println("[app] [Monitor] elements: " + strconv.FormatInt(amount, 10))
}
return
}
func (mms *MqttMonitor) getDataFromIter(iter iterator.Iterator) (lastSeen LastSeenEvent, err error) {
@ -70,13 +73,14 @@ func (mms *MqttMonitor) getDataFromIter(iter iterator.Iterator) (lastSeen LastSe
value := iter.Value()
err = json.Unmarshal(value, &lastSeen)
if err != nil {
mms.Log("[Monitor] Failed to unmarshal entry: " + string(key) + " - " + err.Error())
log.Println("[app] [Monitor] Failed to unmarshal entry: " + string(key) + " - " + err.Error())
}
return
}
func (mms *MqttMonitor) CleanupDB() {
// Create an iterator for the database
log.Println("[app] [Monitor] Starting clean-up process")
iter := mms.db.NewIterator(nil, nil)
defer iter.Release() // Make sure to release the iterator at the end
@ -85,7 +89,7 @@ func (mms *MqttMonitor) CleanupDB() {
// Use iter.Key() and iter.Value() to access the key and value
lastSeen, err := mms.getDataFromIter(iter)
if err != nil {
mms.Log("[Monitor] Failed to unmarshal entry: " + string(iter.Key()) + " - " + err.Error())
log.Println("[app] [Monitor] Failed to unmarshal entry: " + string(iter.Key()) + " - " + err.Error())
continue
}
timeThreshold := time.Now().Add(-1 * mms.CleanupPeriodicityInMinutes * time.Minute).Unix()
@ -93,13 +97,15 @@ func (mms *MqttMonitor) CleanupDB() {
// If the entry is older than 12 hours, delete it
err := mms.deleteEntry(iter.Key())
if err != nil {
mms.Log("[Monitor] Failed to delete entry: " + err.Error())
log.Println("[app] [Monitor] Failed to delete entry: " + err.Error())
} else {
log.Println("[app] [Monitor] Delete entry: " + string(iter.Key()))
}
}
}
// Check for any errors encountered during iteration
if err := iter.Error(); err != nil {
mms.Log(err.Error())
log.Println("[app] [Monitor] error during cleanup : " + err.Error())
}
}

View File

@ -3,7 +3,6 @@ package monitor
import (
"sync"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/planetmint/planetmint-go/config"
"github.com/syndtr/goleveldb/leveldb"
)
@ -11,11 +10,10 @@ import (
type MQTTMonitorClientI interface {
AddParticipant(address string, lastSeenTS int64) (err error)
SelectPoPParticipantsOutOfActiveActors() (challenger string, challengee string, err error)
SetContext(ctx sdk.Context)
Start() (err error)
}
var monitorMutex sync.Mutex
var monitorMutex sync.RWMutex
var mqttMonitorInstance MQTTMonitorClientI
func SetMqttMonitorInstance(monitorInstance MQTTMonitorClientI) {
@ -25,9 +23,9 @@ func SetMqttMonitorInstance(monitorInstance MQTTMonitorClientI) {
}
func LazyMqttMonitorLoader(homeDir string) {
monitorMutex.Lock()
monitorMutex.RLock()
tmpInstance := mqttMonitorInstance
monitorMutex.Unlock()
monitorMutex.RUnlock()
if tmpInstance != nil {
return
}
@ -38,25 +36,18 @@ func LazyMqttMonitorLoader(homeDir string) {
if err != nil {
panic(err)
}
monitorMutex.Lock()
mqttMonitorInstance = NewMqttMonitorService(aciveActorsDB, *config.GetConfig())
monitorMutex.Unlock()
SetMqttMonitorInstance(NewMqttMonitorService(aciveActorsDB, *config.GetConfig()))
err = mqttMonitorInstance.Start()
if err != nil {
panic(err)
}
}
func SetContext(ctx sdk.Context) {
monitorMutex.Lock()
mqttMonitorInstance.SetContext(ctx)
monitorMutex.Unlock()
}
func SelectPoPParticipantsOutOfActiveActors() (challenger string, challengee string, err error) {
monitorMutex.Lock()
monitorMutex.RLock()
challenger, challengee, err = mqttMonitorInstance.SelectPoPParticipantsOutOfActiveActors()
monitorMutex.Unlock()
monitorMutex.RUnlock()
return
}
@ -66,8 +57,8 @@ func Start() (err error) {
}
func AddParticipant(address string, lastSeenTS int64) (err error) {
monitorMutex.Lock()
monitorMutex.RLock()
err = mqttMonitorInstance.AddParticipant(address, lastSeenTS)
monitorMutex.Unlock()
monitorMutex.RUnlock()
return
}

View File

@ -1,8 +1,6 @@
package mocks
import (
types "github.com/cosmos/cosmos-sdk/types"
)
import "log"
// MockMQTTMonitorClientI is a mock of MQTTMonitorClientI interface.
type MockMQTTMonitorClientI struct {
@ -11,6 +9,7 @@ type MockMQTTMonitorClientI struct {
// AddParticipant mocks base method.
func (m *MockMQTTMonitorClientI) AddParticipant(address string, _ int64) error {
log.Println("[app] [Monitor] [Mock] added participant: " + address)
m.myStringList = append(m.myStringList, address)
return nil
@ -24,13 +23,10 @@ func (m *MockMQTTMonitorClientI) SelectPoPParticipantsOutOfActiveActors() (strin
challenger = m.myStringList[amount-2]
challengee = m.myStringList[amount-1]
}
log.Println("[app] [Monitor] [Mock] participants: " + challenger + ", " + challengee)
return challenger, challengee, nil
}
// SetContext mocks base method.
func (m *MockMQTTMonitorClientI) SetContext(_ types.Context) {
}
// Start mocks base method.
func (m *MockMQTTMonitorClientI) Start() error {
return nil

View File

@ -1,9 +1,14 @@
package monitor
import (
"context"
"crypto/tls"
"encoding/json"
"io"
"log"
"math/rand"
"net"
"net/http"
"strconv"
"strings"
"sync"
@ -21,14 +26,19 @@ var MonitorMQTTClient util.MQTTClientI
type MqttMonitor struct {
db *leveldb.DB
dbMutex sync.Mutex // Mutex to synchronize write operations
ticker *time.Ticker
CleanupPeriodicityInMinutes time.Duration
config config.Config
numberOfElementsMutex sync.RWMutex
numberOfElements int64
sdkContext *sdk.Context
contextMutex sync.Mutex
isTerminated bool
terminationMutex sync.Mutex
terminationMutex sync.RWMutex
maxRetries time.Duration
lostConnection bool
lostConnectionMutex sync.Mutex
clientMutex sync.Mutex
localMqttClient util.MQTTClientI
}
func (mms *MqttMonitor) Terminate() {
@ -38,15 +48,32 @@ func (mms *MqttMonitor) Terminate() {
}
func (mms *MqttMonitor) IsTerminated() (isTerminated bool) {
mms.terminationMutex.Lock()
mms.terminationMutex.RLock()
isTerminated = mms.isTerminated
mms.terminationMutex.Unlock()
mms.terminationMutex.RUnlock()
return
}
func LazyLoadMonitorMQTTClient() {
func (mms *MqttMonitor) getNumDBElements() int64 {
mms.numberOfElementsMutex.RLock()
defer mms.numberOfElementsMutex.RUnlock()
return mms.numberOfElements
}
func (mms *MqttMonitor) setNumDBElements(numElements int64) {
mms.numberOfElementsMutex.Lock()
defer mms.numberOfElementsMutex.Unlock()
mms.numberOfElements = numElements
}
func getClientID() string {
conf := config.GetConfig()
return "monitor-" + conf.ValidatorAddress
}
func (mms *MqttMonitor) lazyLoadMonitorMQTTClient() util.MQTTClientI {
if MonitorMQTTClient != nil {
return
return MonitorMQTTClient
}
conf := config.GetConfig()
@ -56,16 +83,19 @@ func LazyLoadMonitorMQTTClient() {
uri = "ssl://" + hostPort
}
opts := mqtt.NewClientOptions().AddBroker(uri)
opts.SetClientID(conf.ValidatorAddress + "-monitor")
opts := mqtt.NewClientOptions().AddBroker(uri).SetKeepAlive(time.Second * 60).SetCleanSession(true)
opts.SetClientID(getClientID())
opts.SetUsername(conf.MqttUser)
opts.SetPassword(conf.MqttPassword)
opts.SetConnectionLostHandler(mms.onConnectionLost)
if conf.MqttTLS {
tlsConfig := &tls.Config{}
opts.SetTLSConfig(tlsConfig)
}
MonitorMQTTClient = mqtt.NewClient(opts)
log.Println("[app] [Monitor] create new client")
client := mqtt.NewClient(opts)
return client
}
func NewMqttMonitorService(db *leveldb.DB, config config.Config) *MqttMonitor {
@ -73,13 +103,20 @@ func NewMqttMonitorService(db *leveldb.DB, config config.Config) *MqttMonitor {
return service
}
func (mms *MqttMonitor) registerPeriodicTasks() {
mms.ticker = time.NewTicker(mms.CleanupPeriodicityInMinutes * time.Minute)
go func() {
for range mms.ticker.C { // Loop over the ticker channel
func (mms *MqttMonitor) runPeriodicTasks() {
tickerRestablishConnection := time.NewTicker(2 * time.Minute)
tickerCleanup := time.NewTicker(5 * time.Minute)
defer tickerRestablishConnection.Stop()
defer tickerCleanup.Stop()
for !mms.IsTerminated() {
select {
case <-tickerRestablishConnection.C:
go mms.MonitorActiveParticipants()
case <-tickerCleanup.C:
go mms.CleanupDB()
}
}()
}
}
func (mms *MqttMonitor) Start() (err error) {
@ -87,36 +124,39 @@ func (mms *MqttMonitor) Start() (err error) {
if err != nil {
return
}
mms.numberOfElements = amount
mms.registerPeriodicTasks()
mms.setNumDBElements(amount)
go mms.runPeriodicTasks()
go mms.MonitorActiveParticipants()
go mms.CleanupDB()
return
}
func (mms *MqttMonitor) getRandomNumbers() (challenger int, challengee int) {
for challenger == challengee {
// Generate random numbers
challenger = rand.Intn(int(mms.numberOfElements))
challengee = rand.Intn(int(mms.numberOfElements))
numElements := int(mms.getNumDBElements())
challenger = rand.Intn(numElements)
challengee = rand.Intn(numElements)
}
return
}
func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger string, challengee string, err error) {
if mms.numberOfElements < 2 {
numElements := int(mms.getNumDBElements())
if numElements < 2 {
return
}
randomChallenger, randomChallengee := mms.getRandomNumbers()
mms.Log("[Monitor] number of elements: " + strconv.Itoa(int(mms.numberOfElements)))
mms.Log("[Monitor] selected IDs: " + strconv.Itoa(randomChallenger) + " " + strconv.Itoa(randomChallengee))
log.Println("[app] [Monitor] number of elements: " + strconv.Itoa(numElements))
log.Println("[app] [Monitor] selected IDs: " + strconv.Itoa(randomChallenger) + " " + strconv.Itoa(randomChallengee))
iter := mms.db.NewIterator(nil, nil)
defer iter.Release()
count := 0
found := 0
var lastSeen LastSeenEvent
for iter.Next() {
mms.Log("[Monitor] count: " + strconv.Itoa(count))
if count == randomChallenger {
lastSeen, err = mms.getDataFromIter(iter)
if err != nil {
log.Println("[app] [Monitor] could not get Data from ID" + strconv.Itoa(randomChallenger))
return
}
challenger = lastSeen.Address
@ -124,6 +164,7 @@ func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger str
} else if count == randomChallengee {
lastSeen, err = mms.getDataFromIter(iter)
if err != nil {
log.Println("[app] [Monitor] could not get Data from ID" + strconv.Itoa(randomChallengee))
return
}
challengee = lastSeen.Address
@ -135,6 +176,7 @@ func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger str
break
}
}
log.Println("[app] [Monitor] challenger, challengee: " + challenger + " " + challengee)
return
}
@ -157,59 +199,183 @@ func (mms *MqttMonitor) MqttMsgHandler(_ mqtt.Client, msg mqtt.Message) {
if err != nil || !valid {
return
}
payload, err := util.ToJSON(msg.Payload())
if err != nil {
active, err := IsLegitMachineAddress(address)
if err != nil || !active {
return
}
timeString, ok := payload["Time"].(string)
if !ok {
return
}
unixTime, err := util.String2UnixTime(timeString)
if err != nil {
return
}
unixTime := time.Now().Unix()
err = mms.AddParticipant(address, unixTime)
if err != nil {
mms.Log("[Monitor] error adding active actor to DB: " + address + " " + err.Error())
log.Println("[app] [Monitor] error adding active actor to DB: " + address + " " + err.Error())
} else {
mms.Log("[Monitor] added active actor to DB: " + address)
log.Println("[app] [Monitor] added active actor to DB: " + address)
}
}
func IsLegitMachineAddress(address string) (active bool, err error) {
url := "http://localhost:1317/planetmint/machine/address/" + address
// Create a new HTTP client
client := &http.Client{}
// Create a new request
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
log.Println("[app] [Monitor] cannot send machine query request " + err.Error())
return
}
// Set the header
req.Header.Set("Accept", "application/json")
// Send the request
resp, err := client.Do(req)
if err != nil {
log.Println("[app] [Monitor] cannot connect to server: " + err.Error())
return
}
// Close the response body
defer resp.Body.Close()
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("[app] [Monitor] cannot read response: " + err.Error())
return
}
// Check the status code
if resp.StatusCode != http.StatusOK {
log.Printf("[app] [Monitor] Error: unexpected status code: " + string(body))
return
}
// Unmarshal the response body into a map
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
log.Println("[app] [Monitor] cannot unmarshal response " + err.Error())
return
}
// Check if the "info" key exists
machineValue, ok := data["machine"]
if !ok {
log.Println("[app] [Monitor] response does not contain the required machine")
return
}
machineMap, ok := machineValue.(map[string]interface{})
if !ok {
log.Println("[app] [Monitor] cannot convert machine map")
return
}
addressMap, ok := machineMap["address"]
if !ok {
log.Println("[app] [Monitor] response does not contain the required name")
return
}
value, ok := addressMap.(string)
if !ok || value != address {
log.Println("[app] [Monitor] return machine is not the required one")
return
}
err = nil
active = true
return
}
func (mms *MqttMonitor) onConnectionLost(_ mqtt.Client, err error) {
log.Println("[app] [Monitor] Connection lost: " + err.Error())
// Handle connection loss here (e.g., reconnect attempts, logging)
if !mms.IsTerminated() {
mms.lostConnectionMutex.Lock()
mms.lostConnection = true
mms.lostConnectionMutex.Unlock()
}
}
func (mms *MqttMonitor) MonitorActiveParticipants() {
LazyLoadMonitorMQTTClient()
for !mms.IsTerminated() {
if !MonitorMQTTClient.IsConnected() {
if token := MonitorMQTTClient.Connect(); token.Wait() && token.Error() != nil {
mms.Log("[Monitor] error connecting to mqtt: " + token.Error().Error())
panic(token.Error())
mms.clientMutex.Lock()
if mms.localMqttClient != nil {
log.Println("[app] [Monitor] client is still working")
mms.clientMutex.Unlock()
return
}
mms.localMqttClient = mms.lazyLoadMonitorMQTTClient()
mqttClient := mms.localMqttClient
mms.clientMutex.Unlock()
// Maximum reconnection attempts (adjust as needed)
mms.SetMaxRetries()
for !mms.IsTerminated() && mms.maxRetries > 0 {
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
log.Println("[app] [Monitor] error connecting to mqtt: " + token.Error().Error())
mms.maxRetries--
time.Sleep(time.Second * 5)
continue
}
mms.lostConnectionMutex.Lock()
mms.lostConnection = false
mms.lostConnectionMutex.Unlock()
log.Println("[app] [Monitor] established connection")
var messageHandler mqtt.MessageHandler = mms.MqttMsgHandler
// Subscribe to a topic
subscriptionTopic := "tele/#"
if token := MonitorMQTTClient.Subscribe(subscriptionTopic, 0, messageHandler); token.Wait() && token.Error() != nil {
mms.Log("[Monitor] error registering the mqtt subscription: " + token.Error().Error())
panic(token.Error())
if token := mqttClient.Subscribe(subscriptionTopic, 0, messageHandler); token.Wait() && token.Error() != nil {
log.Println("[app] [Monitor] error registering the mqtt subscription: " + token.Error().Error())
continue
}
log.Println("[app] [Monitor] subscribed to tele/# channels")
for !mms.IsTerminated() {
mms.lostConnectionMutex.Lock()
lostConnectionEvent := mms.lostConnection
mms.lostConnectionMutex.Unlock()
if !mqttClient.IsConnected() || !mqttClient.IsConnectionOpen() || lostConnectionEvent {
log.Println("[app] [Monitor] retry establishing a connection")
break // Exit inner loop on disconnect
}
SendUpdateMessage(mqttClient)
mms.SetMaxRetries()
time.Sleep(60 * time.Second) // Adjust sleep time based on your needs
}
}
time.Sleep(5 * time.Second)
if mms.maxRetries == 0 {
log.Println("[app] [Monitor] Reached maximum reconnection attempts. Exiting. New client will be activated soon.")
}
mms.clientMutex.Lock()
mms.localMqttClient = nil
mms.clientMutex.Unlock()
}
func SendUpdateMessage(mqttClient util.MQTTClientI) {
// Publish message
now := time.Now().Format("2006-01-02 15:04:05") // Adjust format as needed
token := mqttClient.Publish("tele/"+getClientID(), 1, false, now)
token.Wait()
}
func (mms *MqttMonitor) SetMaxRetries() {
mms.maxRetries = 5
}
func (mms *MqttMonitor) Log(msg string) {
mms.contextMutex.Lock()
if mms.sdkContext != nil {
util.GetAppLogger().Info(*mms.sdkContext, msg)
}
localContext := mms.sdkContext
mms.contextMutex.Unlock()
if localContext != nil {
util.GetAppLogger().Info(*localContext, msg)
}
func (mms *MqttMonitor) SetContext(ctx sdk.Context) {
mms.contextMutex.Lock()
mms.sdkContext = &ctx
mms.contextMutex.Unlock()
}

View File

@ -23,7 +23,6 @@ const (
)
func TestGMonitorActiveParticipants(t *testing.T) {
monitor.LazyLoadMonitorMQTTClient()
cfg := config.GetConfig()
db, err := leveldb.Open(storage.NewMemStorage(), nil)
assert.NoError(t, err)
@ -49,8 +48,6 @@ func TestGMonitorActiveParticipants(t *testing.T) {
}
func TestCleanupRemoval(t *testing.T) {
monitor.LazyLoadMonitorMQTTClient()
cfg := config.GetConfig()
db, err := leveldb.Open(storage.NewMemStorage(), nil)
assert.NoError(t, err)
@ -77,8 +74,6 @@ func TestCleanupRemoval(t *testing.T) {
}
func TestCleanupPrecisionTest(t *testing.T) {
monitor.LazyLoadMonitorMQTTClient()
cfg := config.GetConfig()
db, err := leveldb.Open(storage.NewMemStorage(), nil)
assert.NoError(t, err)
@ -104,3 +99,10 @@ func TestCleanupPrecisionTest(t *testing.T) {
assert.Contains(t, challengee, "plmnt")
mqttMonitor.Terminate()
}
func TestIsLegitMachineAddress(t *testing.T) {
t.SkipNow()
active, err := monitor.IsLegitMachineAddress("plmnt1z6xmwqfnn9mvean9gsd57segawgjykpxw8hq5t")
assert.NoError(t, err)
assert.Equal(t, active, true)
}

View File

@ -1,8 +0,0 @@
syntax = "proto3";
package planetmintgo.asset;
option go_package = "github.com/planetmint/planetmint-go/x/asset/types";
message Asset {
string cid = 1;
}

View File

@ -20,7 +20,7 @@ service Query {
// Queries a list of GetCIDsByAddress items.
rpc GetCIDsByAddress (QueryGetCIDsByAddressRequest) returns (QueryGetCIDsByAddressResponse) {
option (google.api.http).get = "/planetmint/asset/address/{address}/{lookupPeriodInMin}";
option (google.api.http).get = "/planetmint/asset/address/{address}/{numElements}";
}
@ -42,7 +42,7 @@ message QueryParamsResponse {
message QueryGetCIDsByAddressRequest {
string address = 1;
uint64 lookupPeriodInMin = 2;
uint64 numElements = 2;
cosmos.base.query.v1beta1.PageRequest pagination = 3;
}

View File

@ -109,6 +109,7 @@ func (s *ConsumptionE2ETestSuite) TestValidatorConsumption() {
out, err := lib.BroadcastTxWithFileLock(val.Address, msgs...)
s.Require().NoError(err)
s.Require().NoError(s.network.WaitForNextBlock())
s.Require().NoError(s.network.WaitForNextBlock())
_, err = clitestutil.GetRawLogFromTxOut(val, out)

View File

@ -164,9 +164,9 @@ func (s *SelectionE2ETestSuite) TestPopSelectionNoActors() {
}
func (s *SelectionE2ETestSuite) TestPopSelectionOneActors() {
err := e2etestutil.AttestMachine(s.network, machines[0].name, machines[0].mnemonic, 0, s.feeDenom)
err := monitor.AddParticipant(machines[0].address, time.Now().Unix())
s.Require().NoError(err)
err = monitor.AddParticipant(machines[0].address, time.Now().Unix())
err = e2etestutil.AttestMachine(s.network, machines[0].name, machines[0].mnemonic, 0, s.feeDenom)
s.Require().NoError(err)
out := s.perpareLocalTest()
@ -176,9 +176,9 @@ func (s *SelectionE2ETestSuite) TestPopSelectionOneActors() {
}
func (s *SelectionE2ETestSuite) TestPopSelectionTwoActors() {
err := e2etestutil.AttestMachine(s.network, machines[1].name, machines[1].mnemonic, 1, s.feeDenom)
err := monitor.AddParticipant(machines[1].address, time.Now().Unix())
s.Require().NoError(err)
err = monitor.AddParticipant(machines[1].address, time.Now().Unix())
err = e2etestutil.AttestMachine(s.network, machines[1].name, machines[1].mnemonic, 1, s.feeDenom)
s.Require().NoError(err)
out := s.perpareLocalTest()
@ -289,6 +289,8 @@ func (s *SelectionE2ETestSuite) TestTokenRedeemClaim() {
s.Require().NoError(err)
s.Require().NoError(s.network.WaitForNextBlock())
s.Require().NoError(s.network.WaitForNextBlock()) // added another waiting block to pass CI test cases (they are a bit slower)
_, err = clitestutil.GetRawLogFromTxOut(val, out)
s.Require().ErrorContains(err, "failed to execute message; message index: 0: expected: plmnt19cl05ztgt8ey6v86hjjjn3thfmpu6q2xtveehc; got: plmnt1kp93kns6hs2066d8qw0uz84fw3vlthewt2ck6p: invalid claim address")

View File

@ -68,6 +68,7 @@ func (s *E2ETestSuite) TestAttestMachine() {
out, err := e2etestutil.BuildSignBroadcastTx(s.T(), val.Address, msg1)
s.Require().NoError(err)
s.Require().NoError(s.network.WaitForNextBlock())
s.Require().NoError(s.network.WaitForNextBlock())
rawLog, err := clitestutil.GetRawLogFromTxOut(val, out)
s.Require().NoError(err)

View File

@ -44,6 +44,10 @@ func FundAccount(network *network.Network, account *keyring.Record, tokenDenom s
return err
}
err = network.WaitForNextBlock()
if err != nil {
return err
}
err = network.WaitForNextBlock()
if err != nil {
return err
@ -99,6 +103,10 @@ func AttestMachine(network *network.Network, name string, mnemonic string, num i
return err
}
err = network.WaitForNextBlock()
if err != nil {
return err
}
err = network.WaitForNextBlock()
if err != nil {
return err

View File

@ -19,6 +19,19 @@ func DeserializeInt64(value []byte) int64 {
return int64(integer - 1)
}
func SerializeUint64(value uint64) []byte {
buf := make([]byte, 8)
// Adding 1 because 0 will be interpreted as nil, which is an invalid key
binary.BigEndian.PutUint64(buf, value+1)
return buf
}
func DeserializeUint64(value []byte) uint64 {
integer := binary.BigEndian.Uint64(value)
// Subtract 1 because addition in serialization
return integer - 1
}
func SerializeString(value string) []byte {
byteArray := []byte(value)
return byteArray

View File

@ -16,7 +16,7 @@ var (
globalApplicationLoggerTag string
appLogger *AppLogger
initAppLogger sync.Once
syncTestingLog sync.Mutex
syncTestingLog sync.RWMutex
)
func init() {
@ -48,13 +48,13 @@ func format(msg string, keyvals ...interface{}) string {
}
func (logger *AppLogger) testingLog(msg string, keyvals ...interface{}) {
syncTestingLog.RLock()
defer syncTestingLog.RUnlock()
if logger.testingLogger == nil {
return
}
msg = format(msg, keyvals...)
syncTestingLog.Lock()
logger.testingLogger.Logf(msg)
syncTestingLog.Unlock()
}
func (logger *AppLogger) Info(ctx sdk.Context, msg string, keyvals ...interface{}) {

View File

@ -15,6 +15,7 @@ type MockMQTTClient struct {
SubscribeFunc func(topic string, qos byte, callback mqtt.MessageHandler) mqtt.Token
UnsubscribeFunc func(topics ...string) mqtt.Token
IsConnectedFunc func() bool
IsConnectionOpenFunc func() bool
connected bool
connectedMutex sync.Mutex
}
@ -129,3 +130,10 @@ func (m *MockMQTTClient) IsConnected() bool {
m.connectedMutex.Unlock()
return connected
}
func (m *MockMQTTClient) IsConnectionOpen() bool {
m.connectedMutex.Lock()
connected := m.connected
m.connectedMutex.Unlock()
return connected
}

View File

@ -23,6 +23,7 @@ type MQTTClientI interface {
Subscribe(topic string, qos byte, callback mqtt.MessageHandler) mqtt.Token
Unsubscribe(topics ...string) mqtt.Token
IsConnected() bool
IsConnectionOpen() bool
}
var (

View File

@ -1,23 +0,0 @@
package util
import (
"time"
)
func String2UnixTime(timeInput string) (int64, error) {
// Layout specifying the format of the input string
// Note: Go uses a specific reference time (Mon Jan 2 15:04:05 MST 2006) to define format layouts
layout := "2006-01-02T15:04:05"
// Parse the string into a time.Time struct in local time zone
parsedTime, err := time.Parse(layout, timeInput)
if err != nil {
return 0, err
}
// Convert to UTC if not already
utcTime := parsedTime.UTC()
unixTime := utcTime.Unix()
return unixTime, nil
}

View File

@ -1,15 +0,0 @@
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestString2UnixTime(t *testing.T) {
t.Parallel()
input := "2024-03-26T11:10:41"
unixTime, err := String2UnixTime(input)
assert.NoError(t, err)
assert.Equal(t, int64(1711451441), unixTime)
}

View File

@ -1,53 +0,0 @@
package util
import (
"encoding/hex"
"errors"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
)
func ValidateSignature(message string, signature string, publicKey string) (bool, error) {
// Convert the message, signature, and public key from hex to bytes
messageBytes, err := hex.DecodeString(message)
if err != nil {
return false, errors.New("invalid message hex string")
}
return ValidateSignatureByteMsg(messageBytes, signature, publicKey)
}
func ValidateSignatureByteMsg(message []byte, signature string, publicKey string) (bool, error) {
// Convert signature, and public key from hex to bytes
signatureBytes, err := hex.DecodeString(signature)
if err != nil {
return false, errors.New("invalid signature hex string")
}
publicKeyBytes, err := hex.DecodeString(publicKey)
if err != nil {
return false, errors.New("invalid public key hex string")
}
// Create a secp256k1 public key object
pubKey := &secp256k1.PubKey{Key: publicKeyBytes}
// Verify the signature
isValid := pubKey.VerifySignature(message, signatureBytes)
if !isValid {
return false, errors.New("invalid signature")
}
return isValid, nil
}
func GetHexPubKey(extPubKey string) (string, error) {
xpubKey, err := hdkeychain.NewKeyFromString(extPubKey)
if err != nil {
return "", err
}
pubKey, err := xpubKey.ECPubKey()
if err != nil {
return "", err
}
byteKey := pubKey.SerializeCompressed()
return hex.EncodeToString(byteKey), nil
}

View File

@ -14,12 +14,12 @@ var _ = strconv.Itoa(0)
func CmdGetByAddress() *cobra.Command {
cmd := &cobra.Command{
Use: "address [address] [lookup-period-in-min]",
Use: "address [address] [num-elements]",
Short: "Query for assets by address",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) (err error) {
reqAddress := args[0]
reqLookupPeriodInMin, err := cast.ToUint64E(args[1])
reqNumElements, err := cast.ToUint64E(args[1])
if err != nil {
return err
}
@ -34,7 +34,7 @@ func CmdGetByAddress() *cobra.Command {
params := &types.QueryGetCIDsByAddressRequest{
Address: reqAddress,
LookupPeriodInMin: reqLookupPeriodInMin,
NumElements: reqNumElements,
}
pageReq, err := client.ReadPageRequest(cmd.Flags())

View File

@ -8,9 +8,36 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k Keeper) setAddresAssetCount(ctx sdk.Context, address string, count uint64) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AssetKey))
store.Set(types.AddressCountKey(address), util.SerializeUint64(count))
}
func (k Keeper) GetAddressAssetCount(ctx sdk.Context, address string) (count uint64, found bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AssetKey))
countBytes := store.Get(types.AddressCountKey(address))
if countBytes == nil {
return 0, false
}
return util.DeserializeUint64(countBytes), true
}
func (k Keeper) incrementAddressAssetCount(ctx sdk.Context, address string) uint64 {
count, _ := k.GetAddressAssetCount(ctx, address)
k.setAddresAssetCount(ctx, address, count+1)
return count + 1
}
func (k Keeper) StoreAddressAsset(ctx sdk.Context, msg types.MsgNotarizeAsset) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AddressPrefix(msg.GetCreator()))
count := k.incrementAddressAssetCount(ctx, msg.GetCreator())
store.Set(util.SerializeUint64(count), []byte(msg.GetCid()))
}
func (k Keeper) StoreAsset(ctx sdk.Context, msg types.MsgNotarizeAsset) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AssetKey))
store.Set(util.SerializeString(msg.GetCid()), []byte(msg.GetCreator()))
k.StoreAddressAsset(ctx, msg)
}
func (k Keeper) GetAsset(ctx sdk.Context, cid string) (msg types.MsgNotarizeAsset, found bool) {
@ -24,18 +51,23 @@ func (k Keeper) GetAsset(ctx sdk.Context, cid string) (msg types.MsgNotarizeAsse
return msg, true
}
func (k Keeper) GetCidsByAddress(ctx sdk.Context, address string) (cids []string, found bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.AssetKey))
reverseIterator := store.ReverseIterator(nil, nil)
defer reverseIterator.Close()
for ; reverseIterator.Valid(); reverseIterator.Next() {
addressBytes := reverseIterator.Value()
cidBytes := reverseIterator.Key()
if string(addressBytes) == address {
cids = append(cids, string(cidBytes))
func (k Keeper) GetAssetByAddressAndID(ctx sdk.Context, address string, id uint64) (cid string, found bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AddressPrefix(address))
cidBytes := store.Get(util.SerializeUint64(id))
if cidBytes == nil {
return cid, false
}
return string(cidBytes), true
}
func (k Keeper) GetAssetsByAddress(ctx sdk.Context, address string, start []byte, end []byte) (cids []string, found bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AddressPrefix(address))
iterator := store.ReverseIterator(start, end)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
cidBytes := iterator.Value()
cids = append(cids, string(cidBytes))
}
return cids, len(cids) > 0
}

View File

@ -6,6 +6,7 @@ import (
"testing"
keepertest "github.com/planetmint/planetmint-go/testutil/keeper"
"github.com/planetmint/planetmint-go/util"
"github.com/planetmint/planetmint-go/x/asset/keeper"
"github.com/planetmint/planetmint-go/x/asset/types"
@ -39,14 +40,43 @@ func TestGetAssetbyCid(t *testing.T) {
}
}
func TestGetAssetByPubKeys(t *testing.T) {
func TestAssetCount(t *testing.T) {
t.Parallel()
keeper, ctx := keepertest.AssetKeeper(t)
_ = createNAsset(keeper, ctx, 10)
assets, found := keeper.GetCidsByAddress(ctx, "plmnt_address")
numItems := 10
items := createNAsset(keeper, ctx, numItems)
count, found := keeper.GetAddressAssetCount(ctx, items[0].Creator)
assert.True(t, found)
assert.Equal(t, len(assets), 5)
assets, found = keeper.GetCidsByAddress(ctx, "plmnt_address1")
assert.Equal(t, uint64(5), count)
count, found = keeper.GetAddressAssetCount(ctx, items[1].Creator)
assert.True(t, found)
assert.Equal(t, len(assets), 5)
assert.Equal(t, uint64(5), count)
}
func TestGetAssetByAddressAndID(t *testing.T) {
t.Parallel()
keeper, ctx := keepertest.AssetKeeper(t)
items := createNAsset(keeper, ctx, 1)
cid, found := keeper.GetAssetByAddressAndID(ctx, items[0].Creator, 1)
assert.True(t, found)
assert.Equal(t, items[0].Cid, cid)
}
func TestGetAssetsByAddress(t *testing.T) {
t.Parallel()
keeper, ctx := keepertest.AssetKeeper(t)
items := createNAsset(keeper, ctx, 10)
cids, found := keeper.GetAssetsByAddress(ctx, items[0].Creator, nil, nil)
assert.True(t, found)
assert.Equal(t, items[8].Cid, cids[0])
assert.Equal(t, items[4].Cid, cids[2])
cids, found = keeper.GetAssetsByAddress(ctx, items[1].Creator, nil, nil)
assert.True(t, found)
assert.Equal(t, items[9].Cid, cids[0])
assert.Equal(t, items[5].Cid, cids[2])
cids, found = keeper.GetAssetsByAddress(ctx, items[0].Creator, util.SerializeUint64(3), nil)
assert.True(t, found)
assert.Equal(t, 3, len(cids))
assert.Equal(t, items[8].Cid, cids[0])
}

View File

@ -0,0 +1,18 @@
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
v2 "github.com/planetmint/planetmint-go/x/asset/migrations/v2"
)
type Migrator struct {
keeper Keeper
}
func NewMigrator(keeper Keeper) Migrator {
return Migrator{keeper: keeper}
}
func (m Migrator) Migrate1to2(ctx sdk.Context) error {
return v2.MigrateStore(ctx, m.keeper.storeKey, m.keeper.cdc)
}

View File

@ -5,6 +5,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/planetmint/planetmint-go/errormsg"
"github.com/planetmint/planetmint-go/util"
"github.com/planetmint/planetmint-go/x/asset/types"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@ -17,7 +18,7 @@ func (k Keeper) GetCIDsByAddress(goCtx context.Context, req *types.QueryGetCIDsB
ctx := sdk.UnwrapSDKContext(goCtx)
cids, found := k.GetCidsByAddress(ctx, req.GetAddress())
cids, found := k.GetAssetsByAddress(ctx, req.GetAddress(), nil, util.SerializeUint64(req.GetNumElements()))
if !found {
return nil, status.Error(codes.NotFound, "no CIDs found")
}

View File

@ -4,6 +4,7 @@ import (
"testing"
keepertest "github.com/planetmint/planetmint-go/testutil/keeper"
"github.com/planetmint/planetmint-go/util"
"github.com/planetmint/planetmint-go/x/asset/types"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@ -16,7 +17,7 @@ func TestGetNotarizedAssetByAddress(t *testing.T) {
keeper, ctx := keepertest.AssetKeeper(t)
wctx := sdk.WrapSDKContext(ctx)
_ = createNAsset(keeper, ctx, 10)
assets, _ := keeper.GetCidsByAddress(ctx, "plmnt_address")
assets, _ := keeper.GetAssetsByAddress(ctx, "plmnt_address", nil, util.SerializeUint64(3))
for _, tc := range []struct {
desc string
request *types.QueryGetCIDsByAddressRequest
@ -25,7 +26,7 @@ func TestGetNotarizedAssetByAddress(t *testing.T) {
}{
{
desc: "cid found",
request: &types.QueryGetCIDsByAddressRequest{Address: "plmnt_address"},
request: &types.QueryGetCIDsByAddressRequest{Address: "plmnt_address", NumElements: 3},
response: &types.QueryGetCIDsByAddressResponse{Cids: assets},
},
{

View File

@ -0,0 +1,39 @@
package v2
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/planetmint/planetmint-go/util"
"github.com/planetmint/planetmint-go/x/asset/types"
)
func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, _ codec.BinaryCodec) error {
store := prefix.NewStore(ctx.KVStore(storeKey), types.KeyPrefix(types.AssetKey))
mapping := make(map[string][][]byte)
// read all cids
iterator := store.Iterator(nil, nil)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
addressBytes := iterator.Value()
cidBytes := iterator.Key()
// map all cids by address
mapping[string(addressBytes)] = append(mapping[string(addressBytes)], cidBytes)
}
// store all cids with new key
for address, cids := range mapping {
assetByAddressStore := prefix.NewStore(ctx.KVStore(storeKey), types.AddressPrefix(address))
for i, cid := range cids {
assetByAddressStore.Set(util.SerializeUint64(uint64(i)), cid)
}
addressAssetCountStore := prefix.NewStore(ctx.KVStore(storeKey), types.KeyPrefix(types.AssetKey))
addressAssetCountStore.Set(types.AddressCountKey(address), util.SerializeUint64(uint64(len(cids))))
}
return nil
}

View File

@ -116,6 +116,11 @@ func NewAppModule(
func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper))
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
m := keeper.NewMigrator(am.keeper)
if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil {
panic(fmt.Errorf("failed to register migration of %s to v2: %w", types.ModuleName, err))
}
}
// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted)
@ -141,7 +146,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw
}
// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1
func (AppModule) ConsensusVersion() uint64 { return 1 }
func (AppModule) ConsensusVersion() uint64 { return 2 }
// BeginBlock contains the logic that is automatically triggered at the beginning of each block
func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {

View File

@ -1,313 +0,0 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: planetmintgo/asset/asset.proto
package types
import (
fmt "fmt"
proto "github.com/cosmos/gogoproto/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type Asset struct {
Cid string `protobuf:"bytes,1,opt,name=cid,proto3" json:"cid,omitempty"`
}
func (m *Asset) Reset() { *m = Asset{} }
func (m *Asset) String() string { return proto.CompactTextString(m) }
func (*Asset) ProtoMessage() {}
func (*Asset) Descriptor() ([]byte, []int) {
return fileDescriptor_03dd37a25f684e6e, []int{0}
}
func (m *Asset) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Asset) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Asset.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Asset) XXX_Merge(src proto.Message) {
xxx_messageInfo_Asset.Merge(m, src)
}
func (m *Asset) XXX_Size() int {
return m.Size()
}
func (m *Asset) XXX_DiscardUnknown() {
xxx_messageInfo_Asset.DiscardUnknown(m)
}
var xxx_messageInfo_Asset proto.InternalMessageInfo
func (m *Asset) GetCid() string {
if m != nil {
return m.Cid
}
return ""
}
func init() {
proto.RegisterType((*Asset)(nil), "planetmintgo.asset.Asset")
}
func init() { proto.RegisterFile("planetmintgo/asset/asset.proto", fileDescriptor_03dd37a25f684e6e) }
var fileDescriptor_03dd37a25f684e6e = []byte{
// 143 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0xc8, 0x49, 0xcc,
0x4b, 0x2d, 0xc9, 0xcd, 0xcc, 0x2b, 0x49, 0xcf, 0xd7, 0x4f, 0x2c, 0x2e, 0x4e, 0x2d, 0x81, 0x90,
0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x42, 0xc8, 0xf2, 0x7a, 0x60, 0x19, 0x25, 0x49, 0x2e,
0x56, 0x47, 0x10, 0x43, 0x48, 0x80, 0x8b, 0x39, 0x39, 0x33, 0x45, 0x82, 0x51, 0x81, 0x51, 0x83,
0x33, 0x08, 0xc4, 0x74, 0xf2, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f,
0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28,
0xc3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x84, 0x99, 0x48, 0x4c,
0xdd, 0xf4, 0x7c, 0xfd, 0x0a, 0xa8, 0x0b, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x4e,
0x30, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x38, 0x8c, 0xdf, 0xa4, 0x00, 0x00, 0x00,
}
func (m *Asset) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Asset) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Asset) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Cid) > 0 {
i -= len(m.Cid)
copy(dAtA[i:], m.Cid)
i = encodeVarintAsset(dAtA, i, uint64(len(m.Cid)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func encodeVarintAsset(dAtA []byte, offset int, v uint64) int {
offset -= sovAsset(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *Asset) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Cid)
if l > 0 {
n += 1 + l + sovAsset(uint64(l))
}
return n
}
func sovAsset(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozAsset(x uint64) (n int) {
return sovAsset(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Asset) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAsset
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Asset: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Asset: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Cid", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAsset
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthAsset
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthAsset
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Cid = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipAsset(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthAsset
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipAsset(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAsset
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAsset
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowAsset
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthAsset
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupAsset
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthAsset
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthAsset = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowAsset = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupAsset = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -14,8 +14,23 @@ const (
MemStoreKey = "mem_asset"
AssetKey = "Asset/value/"
CountKey = "count/"
)
func AddressCountKey(address string) (prefix []byte) {
addressPrefix := AddressPrefix(address)
prefix = append(prefix, addressPrefix...)
prefix = append(prefix, []byte(CountKey)...)
return
}
func AddressPrefix(address string) (prefix []byte) {
addressBytes := []byte(address)
prefix = append(prefix, addressBytes...)
prefix = append(prefix, []byte("/")...)
return
}
func KeyPrefix(p string) []byte {
return []byte(p)
}

View File

@ -115,7 +115,7 @@ func (m *QueryParamsResponse) GetParams() Params {
type QueryGetCIDsByAddressRequest struct {
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
LookupPeriodInMin uint64 `protobuf:"varint,2,opt,name=lookupPeriodInMin,proto3" json:"lookupPeriodInMin,omitempty"`
NumElements uint64 `protobuf:"varint,2,opt,name=numElements,proto3" json:"numElements,omitempty"`
Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"`
}
@ -159,9 +159,9 @@ func (m *QueryGetCIDsByAddressRequest) GetAddress() string {
return ""
}
func (m *QueryGetCIDsByAddressRequest) GetLookupPeriodInMin() uint64 {
func (m *QueryGetCIDsByAddressRequest) GetNumElements() uint64 {
if m != nil {
return m.LookupPeriodInMin
return m.NumElements
}
return 0
}
@ -333,42 +333,41 @@ func init() {
func init() { proto.RegisterFile("planetmintgo/asset/query.proto", fileDescriptor_5832a953a81817c0) }
var fileDescriptor_5832a953a81817c0 = []byte{
// 547 bytes of a gzipped FileDescriptorProto
// 541 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xcf, 0x6e, 0xd3, 0x30,
0x18, 0x6f, 0xda, 0x52, 0x34, 0x73, 0xd9, 0xcc, 0x0e, 0x51, 0xd8, 0xb2, 0x2a, 0x48, 0x5b, 0x85,
0x20, 0x26, 0xe5, 0x00, 0x9c, 0xd0, 0x0a, 0x62, 0x9a, 0xf8, 0x57, 0x72, 0xe4, 0xe6, 0x26, 0x56,
0xb0, 0x68, 0xed, 0x2c, 0x76, 0x11, 0xa5, 0xf4, 0xc2, 0x13, 0x20, 0xf1, 0x00, 0xbc, 0x01, 0x67,
0x1e, 0x61, 0xc7, 0x49, 0x5c, 0x38, 0x21, 0x68, 0x79, 0x10, 0x14, 0xdb, 0x55, 0x1b, 0xd2, 0x32,
0xed, 0xf6, 0xd5, 0xdf, 0xf7, 0xfb, 0xd3, 0xdf, 0xf7, 0x29, 0xc0, 0x4d, 0xfb, 0x98, 0x11, 0x39,
0xa0, 0x4c, 0x26, 0x1c, 0x61, 0x21, 0x88, 0x44, 0x27, 0x43, 0x92, 0x8d, 0xfc, 0x34, 0xe3, 0x92,
0x43, 0xb8, 0xdc, 0xf7, 0x55, 0xdf, 0xd9, 0x4e, 0x78, 0xc2, 0x55, 0x1b, 0xe5, 0x95, 0x9e, 0x74,
0x76, 0x12, 0xce, 0x93, 0x3e, 0x41, 0x38, 0xa5, 0x08, 0x33, 0xc6, 0x25, 0x96, 0x94, 0x33, 0x61,
0xba, 0x37, 0x22, 0x2e, 0x06, 0x5c, 0xa0, 0x1e, 0x16, 0x44, 0x0b, 0xa0, 0xb7, 0x41, 0x8f, 0x48,
0x1c, 0xa0, 0x14, 0x27, 0x94, 0xa9, 0x61, 0x33, 0xbb, 0xb7, 0xc2, 0x53, 0x8a, 0x33, 0x3c, 0x30,
0x64, 0xde, 0x36, 0x80, 0x2f, 0x73, 0x8a, 0xae, 0x7a, 0x0c, 0xc9, 0xc9, 0x90, 0x08, 0xe9, 0xbd,
0x00, 0x57, 0x0b, 0xaf, 0x22, 0xe5, 0x4c, 0x10, 0x78, 0x0f, 0x34, 0x34, 0xd8, 0xb6, 0x9a, 0x56,
0xeb, 0x4a, 0xdb, 0xf1, 0xcb, 0x7f, 0xc9, 0xd7, 0x98, 0x4e, 0xfd, 0xf4, 0xe7, 0x5e, 0x25, 0x34,
0xf3, 0xde, 0x57, 0x0b, 0xec, 0x28, 0xc6, 0x23, 0x22, 0x1f, 0x1e, 0x3f, 0x12, 0x9d, 0xd1, 0x61,
0x1c, 0x67, 0x44, 0xcc, 0x15, 0xa1, 0x0d, 0x2e, 0x63, 0xfd, 0xa2, 0xb8, 0x37, 0xc2, 0xf9, 0x4f,
0x78, 0x13, 0x6c, 0xf5, 0x39, 0x7f, 0x33, 0x4c, 0xbb, 0x24, 0xa3, 0x3c, 0x3e, 0x66, 0xcf, 0x28,
0xb3, 0xab, 0x4d, 0xab, 0x55, 0x0f, 0xcb, 0x0d, 0xf8, 0x18, 0x80, 0x45, 0x08, 0x76, 0x4d, 0xd9,
0xdc, 0xf7, 0x75, 0x62, 0x7e, 0x9e, 0x98, 0xaf, 0x57, 0x62, 0x12, 0xf3, 0xbb, 0x38, 0x21, 0xc6,
0x43, 0xb8, 0x84, 0xf4, 0x3e, 0x80, 0xdd, 0x35, 0x7e, 0x4d, 0x16, 0x10, 0xd4, 0x23, 0x1a, 0xe7,
0x6e, 0x6b, 0xad, 0x8d, 0x50, 0xd5, 0xf0, 0xa8, 0x20, 0x5e, 0x55, 0xe2, 0x07, 0xe7, 0x8a, 0x6b,
0xc2, 0x82, 0x7a, 0xb0, 0x50, 0x7f, 0xce, 0x25, 0xce, 0xe8, 0x7b, 0x12, 0x1f, 0xe6, 0xe9, 0xce,
0xe3, 0xda, 0x04, 0xb5, 0x88, 0xc6, 0x26, 0xaa, 0xbc, 0xf4, 0x9e, 0x02, 0x77, 0x1d, 0xc4, 0x38,
0x2e, 0x61, 0x96, 0x43, 0xaf, 0x16, 0x42, 0x6f, 0xff, 0xae, 0x81, 0x4b, 0x8a, 0x0e, 0x8e, 0x41,
0x43, 0x6f, 0x14, 0xee, 0xaf, 0xda, 0x76, 0xf9, 0x78, 0x9c, 0x83, 0x73, 0xe7, 0xb4, 0x21, 0xaf,
0xf9, 0xf1, 0xfb, 0x9f, 0xcf, 0x55, 0x07, 0xda, 0x68, 0x01, 0x28, 0xdc, 0x28, 0xfc, 0x66, 0x81,
0xcd, 0x7f, 0x37, 0x00, 0x6f, 0xaf, 0xe5, 0x5f, 0x73, 0x5c, 0x4e, 0x70, 0x01, 0x84, 0xf1, 0xf6,
0x40, 0x79, 0xbb, 0x0f, 0xef, 0x96, 0xbd, 0x99, 0x8c, 0xd0, 0xd8, 0x14, 0x13, 0x34, 0x2e, 0xdd,
0xe1, 0x04, 0x7e, 0xb1, 0xc0, 0x56, 0x69, 0x17, 0xf0, 0xbf, 0x4e, 0x56, 0xae, 0xda, 0x69, 0x5f,
0x04, 0x62, 0xdc, 0x5f, 0x57, 0xee, 0x77, 0xe1, 0xb5, 0xb2, 0xfb, 0x88, 0xc6, 0x68, 0x1c, 0xd1,
0x78, 0xd2, 0x79, 0x72, 0x3a, 0x75, 0xad, 0xb3, 0xa9, 0x6b, 0xfd, 0x9a, 0xba, 0xd6, 0xa7, 0x99,
0x5b, 0x39, 0x9b, 0xb9, 0x95, 0x1f, 0x33, 0xb7, 0xf2, 0x2a, 0x48, 0xa8, 0x7c, 0x3d, 0xec, 0xf9,
0x11, 0x1f, 0x2c, 0x13, 0x2c, 0xca, 0x5b, 0x09, 0x47, 0xef, 0x0c, 0xa1, 0x1c, 0xa5, 0x44, 0xf4,
0x1a, 0xea, 0x73, 0x72, 0xe7, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x76, 0xa1, 0xdb, 0x5c, 0x05,
0x05, 0x00, 0x00,
0x18, 0x6f, 0xda, 0x51, 0x34, 0xef, 0x32, 0xcc, 0x0e, 0x51, 0xd8, 0xb2, 0x2a, 0x48, 0x5b, 0x85,
0x44, 0x4c, 0xba, 0x0b, 0x1c, 0x57, 0xfe, 0x4c, 0x08, 0x04, 0x23, 0x47, 0x6e, 0x6e, 0x62, 0x05,
0x4b, 0x8d, 0x9d, 0xc5, 0x2e, 0xa2, 0x94, 0x5e, 0x78, 0x02, 0x24, 0x1e, 0x00, 0x89, 0x47, 0xe0,
0x29, 0x76, 0x9c, 0xc4, 0x05, 0x09, 0x09, 0xa1, 0x96, 0x07, 0x41, 0xb1, 0x5d, 0x35, 0x21, 0x2d,
0xd3, 0x6e, 0x5f, 0xec, 0xef, 0xf7, 0xc7, 0xbf, 0xef, 0x53, 0x80, 0x9b, 0x0d, 0x31, 0x23, 0x32,
0xa5, 0x4c, 0x26, 0x1c, 0x61, 0x21, 0x88, 0x44, 0x67, 0x23, 0x92, 0x8f, 0xfd, 0x2c, 0xe7, 0x92,
0x43, 0x58, 0xbe, 0xf7, 0xd5, 0xbd, 0xb3, 0x93, 0xf0, 0x84, 0xab, 0x6b, 0x54, 0x54, 0xba, 0xd3,
0xd9, 0x4d, 0x38, 0x4f, 0x86, 0x04, 0xe1, 0x8c, 0x22, 0xcc, 0x18, 0x97, 0x58, 0x52, 0xce, 0x84,
0xb9, 0xbd, 0x13, 0x71, 0x91, 0x72, 0x81, 0x06, 0x58, 0x10, 0x2d, 0x80, 0xde, 0x06, 0x03, 0x22,
0x71, 0x80, 0x32, 0x9c, 0x50, 0xa6, 0x9a, 0x4d, 0xef, 0xfe, 0x0a, 0x4f, 0x19, 0xce, 0x71, 0x6a,
0xc8, 0xbc, 0x1d, 0x00, 0x5f, 0x15, 0x14, 0xa7, 0xea, 0x30, 0x24, 0x67, 0x23, 0x22, 0xa4, 0xf7,
0x12, 0xdc, 0xac, 0x9c, 0x8a, 0x8c, 0x33, 0x41, 0xe0, 0x7d, 0xd0, 0xd6, 0x60, 0xdb, 0xea, 0x58,
0xdd, 0xad, 0x9e, 0xe3, 0xd7, 0x9f, 0xe4, 0x6b, 0x4c, 0x7f, 0xe3, 0xfc, 0xd7, 0x7e, 0x23, 0x34,
0xfd, 0xde, 0x57, 0x0b, 0xec, 0x2a, 0xc6, 0x13, 0x22, 0x1f, 0x3e, 0x7d, 0x24, 0xfa, 0xe3, 0xe3,
0x38, 0xce, 0x89, 0x58, 0x28, 0x42, 0x1b, 0x5c, 0xc7, 0xfa, 0x44, 0x71, 0x6f, 0x86, 0x8b, 0x4f,
0xd8, 0x01, 0x5b, 0x6c, 0x94, 0x3e, 0x1e, 0x92, 0x94, 0x30, 0x29, 0xec, 0x66, 0xc7, 0xea, 0x6e,
0x84, 0xe5, 0x23, 0xf8, 0x04, 0x80, 0xe5, 0xc3, 0xed, 0x96, 0xb2, 0x76, 0xe0, 0xeb, 0x94, 0xfc,
0x22, 0x25, 0x5f, 0x8f, 0xc1, 0xa4, 0xe4, 0x9f, 0xe2, 0x84, 0x18, 0xdd, 0xb0, 0x84, 0xf4, 0x3e,
0x80, 0xbd, 0x35, 0x1e, 0xcd, 0xfb, 0x21, 0xd8, 0x88, 0x68, 0x5c, 0x38, 0x6c, 0x75, 0x37, 0x43,
0x55, 0xc3, 0x93, 0x8a, 0x78, 0x53, 0x89, 0x1f, 0x5e, 0x2a, 0xae, 0x09, 0x2b, 0xea, 0xc1, 0x52,
0xfd, 0x05, 0x97, 0x38, 0xa7, 0xef, 0x49, 0x7c, 0x5c, 0x24, 0xba, 0x88, 0x68, 0x1b, 0xb4, 0x22,
0x1a, 0x9b, 0x78, 0x8a, 0xd2, 0x7b, 0x0e, 0xdc, 0x75, 0x10, 0xe3, 0xb8, 0x86, 0x29, 0x07, 0xdd,
0xac, 0x04, 0xdd, 0xfb, 0xd9, 0x02, 0xd7, 0x14, 0x1d, 0x9c, 0x80, 0xb6, 0x9e, 0x22, 0x3c, 0x58,
0x35, 0xe1, 0xfa, 0xc2, 0x38, 0x87, 0x97, 0xf6, 0x69, 0x43, 0x5e, 0xe7, 0xe3, 0xf7, 0x3f, 0x9f,
0x9b, 0x0e, 0xb4, 0xd1, 0x12, 0x50, 0xd9, 0x4b, 0xf8, 0xcd, 0x02, 0xdb, 0xff, 0x4e, 0x00, 0xde,
0x5b, 0xcb, 0xbf, 0x66, 0xa1, 0x9c, 0xe0, 0x0a, 0x08, 0xe3, 0xed, 0x81, 0xf2, 0x76, 0x04, 0x83,
0xba, 0x37, 0x93, 0x11, 0x9a, 0x98, 0x62, 0x8a, 0x26, 0xa5, 0x0d, 0x9c, 0xc2, 0x2f, 0x16, 0xb8,
0x51, 0x9b, 0x02, 0xfc, 0xaf, 0x87, 0x95, 0x43, 0x76, 0x7a, 0x57, 0x81, 0x18, 0xdf, 0xb7, 0x95,
0xef, 0x3d, 0x78, 0xab, 0xee, 0x3b, 0xa2, 0x31, 0x9a, 0x44, 0x34, 0x9e, 0xf6, 0x9f, 0x9d, 0xcf,
0x5c, 0xeb, 0x62, 0xe6, 0x5a, 0xbf, 0x67, 0xae, 0xf5, 0x69, 0xee, 0x36, 0x2e, 0xe6, 0x6e, 0xe3,
0xc7, 0xdc, 0x6d, 0xbc, 0x0e, 0x12, 0x2a, 0xdf, 0x8c, 0x06, 0x7e, 0xc4, 0xd3, 0x32, 0xc1, 0xb2,
0xbc, 0x9b, 0x70, 0xf4, 0xce, 0x10, 0xca, 0x71, 0x46, 0xc4, 0xa0, 0xad, 0x7e, 0x1e, 0x47, 0x7f,
0x03, 0x00, 0x00, 0xff, 0xff, 0xb3, 0x7e, 0xf6, 0x2a, 0xf3, 0x04, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
@ -617,8 +616,8 @@ func (m *QueryGetCIDsByAddressRequest) MarshalToSizedBuffer(dAtA []byte) (int, e
i--
dAtA[i] = 0x1a
}
if m.LookupPeriodInMin != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.LookupPeriodInMin))
if m.NumElements != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.NumElements))
i--
dAtA[i] = 0x10
}
@ -784,8 +783,8 @@ func (m *QueryGetCIDsByAddressRequest) Size() (n int) {
if l > 0 {
n += 1 + l + sovQuery(uint64(l))
}
if m.LookupPeriodInMin != 0 {
n += 1 + sovQuery(uint64(m.LookupPeriodInMin))
if m.NumElements != 0 {
n += 1 + sovQuery(uint64(m.NumElements))
}
if m.Pagination != nil {
l = m.Pagination.Size()
@ -1045,9 +1044,9 @@ func (m *QueryGetCIDsByAddressRequest) Unmarshal(dAtA []byte) error {
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field LookupPeriodInMin", wireType)
return fmt.Errorf("proto: wrong wireType = %d for field NumElements", wireType)
}
m.LookupPeriodInMin = 0
m.NumElements = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
@ -1057,7 +1056,7 @@ func (m *QueryGetCIDsByAddressRequest) Unmarshal(dAtA []byte) error {
}
b := dAtA[iNdEx]
iNdEx++
m.LookupPeriodInMin |= uint64(b&0x7F) << shift
m.NumElements |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}

View File

@ -52,7 +52,7 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal
}
var (
filter_Query_GetCIDsByAddress_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0, "lookupPeriodInMin": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}}
filter_Query_GetCIDsByAddress_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0, "numElements": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}}
)
func request_Query_GetCIDsByAddress_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
@ -77,15 +77,15 @@ func request_Query_GetCIDsByAddress_0(ctx context.Context, marshaler runtime.Mar
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err)
}
val, ok = pathParams["lookupPeriodInMin"]
val, ok = pathParams["numElements"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "lookupPeriodInMin")
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "numElements")
}
protoReq.LookupPeriodInMin, err = runtime.Uint64(val)
protoReq.NumElements, err = runtime.Uint64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "lookupPeriodInMin", err)
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "numElements", err)
}
if err := req.ParseForm(); err != nil {
@ -122,15 +122,15 @@ func local_request_Query_GetCIDsByAddress_0(ctx context.Context, marshaler runti
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err)
}
val, ok = pathParams["lookupPeriodInMin"]
val, ok = pathParams["numElements"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "lookupPeriodInMin")
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "numElements")
}
protoReq.LookupPeriodInMin, err = runtime.Uint64(val)
protoReq.NumElements, err = runtime.Uint64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "lookupPeriodInMin", err)
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "numElements", err)
}
if err := req.ParseForm(); err != nil {
@ -381,7 +381,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie
var (
pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"planetmint", "asset", "params"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetCIDsByAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3}, []string{"planetmint", "asset", "address", "lookupPeriodInMin"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetCIDsByAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3}, []string{"planetmint", "asset", "address", "numElements"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Query_GetNotarizedAsset_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 2}, []string{"planetmint", "asset", "cid"}, "", runtime.AssumeColonVerbOpt(true)))
)

View File

@ -24,7 +24,6 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper)
hexProposerAddress := hex.EncodeToString(proposerAddress)
if isPopHeight(ctx, k, currentBlockHeight) {
// select PoP participants
monitor.SetContext(ctx)
challenger, challengee, err := monitor.SelectPoPParticipantsOutOfActiveActors()
if err != nil {
util.GetAppLogger().Error(ctx, "error during PoP Participant selection ", err)

View File

@ -2,6 +2,7 @@ package keeper
import (
"context"
"errors"
"fmt"
config "github.com/planetmint/planetmint-go/config"
@ -13,6 +14,7 @@ import (
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/rddl-network/go-utils/signature"
)
func (k msgServer) AttestMachine(goCtx context.Context, msg *types.MsgAttestMachine) (*types.MsgAttestMachineResponse, error) {
@ -22,9 +24,17 @@ func (k msgServer) AttestMachine(goCtx context.Context, msg *types.MsgAttestMach
// and removed from here due to inconsistency or checking the same thing over and over again.
ta, _, _ := k.GetTrustAnchor(ctx, msg.Machine.MachineId)
isValidMachineID, err := util.ValidateSignature(msg.Machine.MachineId, msg.Machine.MachineIdSignature, msg.Machine.MachineId)
if !isValidMachineID {
return nil, err
isValidSecp256r1, errR1 := signature.ValidateSECP256R1Signature(msg.Machine.MachineId, msg.Machine.MachineIdSignature, msg.Machine.MachineId)
if errR1 != nil || !isValidSecp256r1 {
isValidSecp256k1, errK1 := signature.ValidateSignature(msg.Machine.MachineId, msg.Machine.MachineIdSignature, msg.Machine.MachineId)
if errK1 != nil || !isValidSecp256k1 {
errStr := ""
if errR1 != nil {
errStr = errR1.Error()
}
aggreatedErrorMessage := "Invalid machine signature: " + errStr + ", " + errK1.Error()
return nil, errors.New(aggreatedErrorMessage)
}
}
isValidIssuerPlanetmint := validateExtendedPublicKey(msg.Machine.IssuerPlanetmint, config.PlmntNetParams)
@ -59,7 +69,7 @@ func (k msgServer) AttestMachine(goCtx context.Context, msg *types.MsgAttestMach
k.StoreMachine(ctx, *msg.Machine)
k.StoreMachineIndex(ctx, *msg.Machine)
err = k.StoreTrustAnchor(ctx, ta, true)
err := k.StoreTrustAnchor(ctx, ta, true)
if err != nil {
return nil, err
}

View File

@ -35,6 +35,12 @@ func validatePublicKey(pubkey string) bool {
return false
}
// uncompressed key
if len(pubkeyBytes) == 64 {
return true
}
// compressed key
// Check if byte slice has correct length
if len(pubkeyBytes) != 33 {
return false

View File

@ -71,6 +71,18 @@ func TestMsgServerRegisterTrustAnchor(t *testing.T) {
}
}
func TestMsgServerRegisterTrustAnchorUncompressedKey(t *testing.T) {
t.Parallel()
pk := "6003d0ab9af4ec112629195a7266a244aecf1ac7691da0084be3e7ceea2ee71571b0963fffd9c80a640317509a681ac66c2ed70ecc9f317a0d2b1a9bff94ff74"
ta := moduleobject.TrustAnchor(pk)
msg := types.NewMsgRegisterTrustAnchor(pk, &ta)
msgServer, ctx := setupMsgServer(t)
res, err := msgServer.RegisterTrustAnchor(ctx, msg)
if assert.NoError(t, err) {
assert.Equal(t, &types.MsgRegisterTrustAnchorResponse{}, res)
}
}
func TestMsgServerRegisterTrustAnchorTwice(t *testing.T) {
t.Parallel()
_, pk := sample.KeyPair()