Skip to content

Commit d9b52a2

Browse files
Resolve misc minor edits / fixes (#255)
* resolve misc minor edits / fixes * minor edit * update test * best test mode check * update event indexer and txn indexer to insert txDigest as a hex string (#201) Co-authored-by: Sishir Giri <[email protected]> * Revert "update event indexer and txn indexer to insert txDigest as a hex stri…" (#256) This reverts commit b4138fa. --------- Co-authored-by: Sishir Giri <[email protected]>
1 parent 7691524 commit d9b52a2

File tree

13 files changed

+115
-25
lines changed

13 files changed

+115
-25
lines changed

relayer/chainreader/chainreader_util/hasher.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ func (h *MessageHasherV1) Hash(ctx context.Context, report *codec.ExecutionRepor
8282
return [32]byte{}, fmt.Errorf("compute metadata hash: %w", err)
8383
}
8484

85+
if len(report.Message.Header.MessageID) != 32 {
86+
h.lggr.Warnw("Invalid message ID length, messageID will be padded or truncated", "messageID", report.Message.Header.MessageID)
87+
}
88+
8589
var messageID [32]byte
8690
copy(messageID[:], report.Message.Header.MessageID)
8791

@@ -169,13 +173,21 @@ func computeMessageDataHash(
169173

170174
// Manually encode tokens to match the Move implementation
171175
var tokenHashData []byte
172-
tokenHashData = append(tokenHashData, encodeUint256(big.NewInt(int64(len(tokenAmounts))))...)
176+
encodedLen, err := encodeUint256(big.NewInt(int64(len(tokenAmounts))))
177+
if err != nil {
178+
return [32]byte{}, fmt.Errorf("failed to encode token length: %w", err)
179+
}
180+
tokenHashData = append(tokenHashData, encodedLen...)
173181
for _, token := range tokenAmounts {
174182
tokenHashData = append(tokenHashData, encodeBytes(token.SourcePoolAddress)...)
175183
tokenHashData = append(tokenHashData, token.DestTokenAddress[:]...)
176184
tokenHashData = append(tokenHashData, encodeUint32(token.DestGasAmount)...)
177185
tokenHashData = append(tokenHashData, encodeBytes(token.ExtraData)...)
178-
tokenHashData = append(tokenHashData, encodeUint256(token.Amount)...)
186+
encodedAmount, err := encodeUint256(token.Amount)
187+
if err != nil {
188+
return [32]byte{}, fmt.Errorf("failed to encode token amount: %w", err)
189+
}
190+
tokenHashData = append(tokenHashData, encodedAmount...)
179191
}
180192
tokenAmountsHash := crypto.Keccak256Hash(tokenHashData)
181193

@@ -242,8 +254,12 @@ func computeMetadataHash(
242254
return metadataHash, nil
243255
}
244256

245-
func encodeUint256(n *big.Int) []byte {
246-
return common.LeftPadBytes(n.Bytes(), 32)
257+
func encodeUint256(n *big.Int) ([]byte, error) {
258+
if n == nil {
259+
return []byte{}, fmt.Errorf("nil big.Int cannot be encoded")
260+
}
261+
262+
return common.LeftPadBytes(n.Bytes(), 32), nil
247263
}
248264

249265
func encodeUint32(n uint32) []byte {

relayer/chainreader/chainreader_util/package_resolver.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,12 @@ func (pr *PackageResolver) InvalidateCache(moduleName string) {
243243
packageAddress := pr.packageAddresses[moduleName]
244244
pr.mutex.RUnlock()
245245

246+
// If the package address is not found, do not invalidate the cache
247+
if packageAddress == "" {
248+
pr.log.Debugw("Package address not found for module, skipping cache invalidation", "module", moduleName)
249+
return
250+
}
251+
246252
keys := []string{
247253
packageAddressCachePrefix + moduleName,
248254
packageIDsCachePrefix + packageAddress + ":" + moduleName,

relayer/chainreader/indexer/transactions_indexer.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,16 @@ func (tIndexer *TransactionsIndexer) syncTransmitterTransactions(ctx context.Con
371371
tIndexer.logger.Debugw("Report arg", "reportArg", reportArg)
372372

373373
// Handle the conversion from []interface{} to []byte
374-
reportValue := reportArg["value"].([]any)
374+
reportValue, ok := reportArg["value"].([]any)
375+
if !ok {
376+
tIndexer.logger.Errorw("Expected report value to be a []any",
377+
"transmitter", transmitter,
378+
"txDigest", transactionRecord.Digest,
379+
"reportArg", reportArg,
380+
"valueType", fmt.Sprintf("%T", reportArg["value"]))
381+
continue
382+
}
383+
375384
reportBytes := make([]byte, len(reportValue))
376385
for i, val := range reportValue {
377386
num, ok := val.(float64)

relayer/chainreader/reader/chainreader.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,12 @@ func (s *suiChainReader) Unbind(ctx context.Context, bindings []pkgtypes.BoundCo
164164
return fmt.Errorf("failed to unbind package %s: %w", binding.Name, err)
165165
}
166166

167+
modulePrefix := fmt.Sprintf("%s::%s::", binding.Address, binding.Name)
168+
167169
// Clear cached parent object IDs for this unbound contract
168170
s.parentObjectIDsMutex.Lock()
169171
for key := range s.parentObjectIDs {
170-
if strings.HasPrefix(key, binding.Address+"::") {
172+
if strings.HasPrefix(key, modulePrefix) {
171173
delete(s.parentObjectIDs, key)
172174
}
173175
}
@@ -1047,7 +1049,11 @@ func (s *suiChainReader) transformEventsToSequences(eventRecords []database.Even
10471049
}
10481050

10491051
for _, record := range eventRecords {
1050-
eventData := reflect.New(reflect.TypeOf(expectedEventType).Elem()).Interface()
1052+
t := reflect.TypeOf(expectedEventType)
1053+
if t == nil || t.Kind() != reflect.Ptr {
1054+
return nil, fmt.Errorf("sequenceDataType must be a non-nil pointer type")
1055+
}
1056+
eventData := reflect.New(t.Elem()).Interface()
10511057

10521058
s.logger.Debugw("Processing database event record", "data", record.Data, "offset", record.EventOffset, "eventDataType", reflect.TypeOf(eventData).Elem())
10531059

relayer/client/ptb_client.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net/http"
99
"strconv"
1010
"strings"
11+
"testing"
1112
"time"
1213

1314
"github.com/aptos-labs/aptos-go-sdk/bcs"
@@ -139,6 +140,11 @@ func NewPTBClient(
139140
) (*PTBClient, error) {
140141
log.Infof("Creating new SUI client with blockvision SDK")
141142

143+
if maxConcurrentRequests <= 0 {
144+
log.Warnw("maxConcurrentRequests is less than 0, setting to default value", "maxConcurrentRequests", maxConcurrentRequests)
145+
maxConcurrentRequests = 500 // Default value
146+
}
147+
142148
httpClient := &http.Client{
143149
Timeout: DefaultHTTPTimeout,
144150
Transport: &http.Transport{
@@ -149,10 +155,6 @@ func NewPTBClient(
149155
}
150156
client := sui.NewSuiClientWithCustomClient(rpcUrl, httpClient)
151157

152-
if maxConcurrentRequests <= 0 {
153-
maxConcurrentRequests = 500 // Default value
154-
}
155-
156158
log.Infof(
157159
"PTBClient config configs transactionTimeout: %s, maxConcurrentRequests: %d",
158160
transactionTimeout,
@@ -825,7 +827,14 @@ func (c *PTBClient) QueryCoinsByAddress(ctx context.Context, address string, coi
825827
return result, err
826828
}
827829

830+
// FinishPTBAndSend finishes the PTB transaction and sends it to the network.
831+
// IMPORTANT: This method is only used for testing purposes.
828832
func (c *PTBClient) FinishPTBAndSend(ctx context.Context, txnSigner *signer.Signer, tx *transaction.Transaction, requestType TransactionRequestType) (SuiTransactionBlockResponse, error) {
833+
// This method should only be used in test environments
834+
if !testing.Testing() {
835+
return SuiTransactionBlockResponse{}, fmt.Errorf("FinishPTBAndSend is only available in test environments")
836+
}
837+
829838
gasPrice, err := c.GetReferenceGasPrice(ctx)
830839
if err != nil {
831840
return SuiTransactionBlockResponse{}, fmt.Errorf("failed to get reference gas price: %w", err)

relayer/codec/decoder_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,8 +475,8 @@ func TestHexStringHook(t *testing.T) {
475475
{
476476
name: "hex to byte array",
477477
data: "0x123456",
478-
target: new([4]uint8),
479-
expected: []uint8{0x12, 0x34, 0x56, 0x00},
478+
target: new([3]uint8),
479+
expected: []uint8{0x12, 0x34, 0x56},
480480
},
481481
}
482482

relayer/codec/encoder.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,21 @@ func encodeAddress(value any) (string, error) {
9292
v = "0x" + v
9393
}
9494

95-
return v, nil
95+
normalizedAddress, err := bind.ToSuiAddress(v)
96+
if err != nil {
97+
return "", fmt.Errorf("failed to convert address to Sui address: %w", err)
98+
}
99+
100+
return normalizedAddress, nil
96101
case []byte:
97-
return "0x" + hex.EncodeToString(v), nil
102+
stringAddr := "0x" + hex.EncodeToString(v)
103+
104+
normalizedAddress, err := bind.ToSuiAddress(stringAddr)
105+
if err != nil {
106+
return "", fmt.Errorf("failed to convert address to Sui address: %w", err)
107+
}
108+
109+
return normalizedAddress, nil
98110
default:
99111
return "", fmt.Errorf("cannot convert %T to address", value)
100112
}
@@ -298,9 +310,17 @@ func encodeVector(typeName string, value any) ([]any, error) {
298310
}
299311
innerType := typeName[len("vector<") : len(typeName)-1]
300312

301-
// Use reflection to ensure 'value' is a slice or array
313+
if value == nil {
314+
return nil, fmt.Errorf("nil value cannot be encoded in encodeVector")
315+
}
302316
rv := reflect.ValueOf(value)
317+
318+
if !rv.IsValid() {
319+
return nil, fmt.Errorf("invalid reflect value for vector type %s in encodeVector", typeName)
320+
}
303321
kind := rv.Kind()
322+
323+
// Use reflection to ensure 'value' is a slice or array
304324
if kind != reflect.Slice && kind != reflect.Array {
305325
return nil, fmt.Errorf("expected a slice/array for vector type %s, got %T", typeName, value)
306326
}

relayer/codec/type_converters.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,11 @@ func (tc *TypeConverter) hexToArray(from, to reflect.Type, data any) (any, error
375375

376376
byteSlice := bytes.([]byte)
377377
out := make([]uint8, to.Len())
378+
379+
if len(byteSlice) != to.Len() {
380+
return nil, fmt.Errorf("hex to array: byte slice length %d is not equal to output array length %d", len(byteSlice), to.Len())
381+
}
382+
378383
copy(out, byteSlice)
379384

380385
return out, nil

relayer/config/toml_config.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,11 @@ func (cs TOMLConfigs) validateKeys() error {
9797
}
9898

9999
func (cs *TOMLConfigs) SetFrom(fs *TOMLConfigs) error {
100+
// Avoids panics if the source TOMLConfigs is nil
101+
if fs == nil {
102+
return nil
103+
}
104+
100105
if err1 := fs.validateKeys(); err1 != nil {
101106
return err1
102107
}
@@ -118,6 +123,11 @@ func (cs *TOMLConfigs) SetFrom(fs *TOMLConfigs) error {
118123
type NodeConfigs []*NodeConfig
119124

120125
func (ns *NodeConfigs) SetFrom(fs *NodeConfigs) {
126+
// Avoids panics if the source NodeConfigs is nil
127+
if fs == nil {
128+
return
129+
}
130+
121131
for _, f := range *fs {
122132
if f.Name == nil {
123133
*ns = append(*ns, f)

relayer/signer/signer.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"encoding/base64"
77
"encoding/hex"
88
"fmt"
9-
"log"
109

1110
"golang.org/x/crypto/blake2b"
1211
)
@@ -104,7 +103,7 @@ func (s *PrivateKeySigner) Sign(message []byte) ([]string, error) {
104103
var noHash crypto.Hash
105104
sigBytes, err := s.privateKey.Sign(nil, digest[:], noHash)
106105
if err != nil {
107-
log.Fatal(err)
106+
return nil, fmt.Errorf("failed to sign message with ed25519: %w", err)
108107
}
109108
pubKey := s.privateKey.Public().(ed25519.PublicKey)
110109
serializedSignature := SerializeSuiSignature(sigBytes, pubKey)

0 commit comments

Comments
 (0)