-
Notifications
You must be signed in to change notification settings - Fork 1
/
checkpoint.go
561 lines (471 loc) · 18.6 KB
/
checkpoint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package types
import (
"encoding/hex"
fmt "fmt"
"math/big"
"strings"
"github.com/NethermindEth/juno/core/felt"
starknetgo "github.com/NethermindEth/starknet.go/curve"
"github.com/NethermindEth/starknet.go/utils"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
multichainTypes "github.com/router-protocol/sdk-go/routerchain/multichain/types"
"github.com/router-protocol/sdk-go/routerchain/util"
)
///////////////////////////////////
// Implement Ccheckpoint //
///////////////////////////////////
// GetCheckpoint gets the checkpoint signature from the given CrossTalkRequest
func (msg MsgCrosschainRequest) GetCheckpoint(routerIDstring string) []byte {
/**
Always get checkpoint from crosschain request only.
Crosschain request is dynamic while msg is static.
**/
crosschainRequest := NewCrosschainRequestFromMsg(&msg)
switch crosschainRequest.DestChainType {
case multichainTypes.CHAIN_TYPE_NEAR, multichainTypes.CHAIN_TYPE_POLKADOT:
return crosschainRequest.GetNearCheckpoint("")
case multichainTypes.CHAIN_TYPE_COSMOS:
return nil
case multichainTypes.CHAIN_TYPE_STARKNET:
return crosschainRequest.GetStarknetCheckpoint("")
case multichainTypes.CHAIN_TYPE_ALEPH_ZERO:
return crosschainRequest.GetAlephZeroCheckpoint("")
default:
return crosschainRequest.GetEvmCheckpoint("")
}
}
// GetCheckpoint gets the checkpoint signature from the given CrossTalkRequest
func (msg CrosschainRequest) GetCheckpoint(routerIDstring string) []byte {
/**
Always get checkpoint from crosschain request only.
Crosschain request is dynamic while msg is static.
**/
switch msg.DestChainType {
case multichainTypes.CHAIN_TYPE_NEAR, multichainTypes.CHAIN_TYPE_POLKADOT:
return msg.GetNearCheckpoint("")
case multichainTypes.CHAIN_TYPE_COSMOS:
return nil
case multichainTypes.CHAIN_TYPE_STARKNET:
return msg.GetStarknetCheckpoint("")
case multichainTypes.CHAIN_TYPE_ALEPH_ZERO:
return msg.GetAlephZeroCheckpoint("")
default:
return msg.GetEvmCheckpoint("")
}
}
func (msg CrosschainRequest) GetAlephZeroCheckpoint(routerIDstring string) []byte {
//////////////////////////////////////////////////////////////////////
///// Build data with types required for iReceive gateway call /////
//////////////////////////////////////////////////////////////////////
metadata := DecodeEvmContractMetadata(&msg)
requestPacket := DecodeRouterCrosschainPacket(&msg)
methodNameBytes := []uint8("iReceive")
var crosschainMethodName [32]uint8
copy(crosschainMethodName[:], methodNameBytes)
routeAmount := msg.RouteAmount.BigInt()
requestIdentifier := &big.Int{}
requestIdentifier.SetUint64(msg.RequestIdentifier)
requestTimestamp := &big.Int{}
requestTimestamp.SetUint64(uint64(msg.SrcTimestamp))
var routeRecipient [32]uint8
routeRecipientByte, err := hex.DecodeString(strings.TrimPrefix(msg.RouteRecipient, "0x"))
if err != nil {
return nil
}
copy(routeRecipient[:], routeRecipientByte)
var asmAddress [32]uint8
asmAddressByte, err := hex.DecodeString(strings.TrimPrefix(metadata.AsmAddress, "0x"))
if err != nil {
return nil
}
copy(asmAddress[:], asmAddressByte)
var handler [32]uint8
handlerByte, err := hex.DecodeString(strings.TrimPrefix(requestPacket.Handler, "0x"))
if err != nil {
return nil
}
copy(handler[:], handlerByte)
/////////////////////////////////////////////////
///// pack abi for iReceive function //////////
/////////////////////////////////////////////////
abiDef, err := abi.JSON(strings.NewReader(util.CrosschainRequestAlephZeroCheckpointABIJSON))
if err != nil {
panic("Bad ABI constant!")
}
// the methodName needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
abiEncodedBatch, err := abiDef.Pack("checkpoint",
crosschainMethodName,
routeAmount,
requestIdentifier,
requestTimestamp,
msg.SrcChainId,
routeRecipient,
msg.DestChainId,
asmAddress,
msg.RequestSender,
handler,
requestPacket.Payload,
metadata.IsReadCall,
)
// fmt.Println("Checkpoint- crosschainMethodName ", crosschainMethodName)
// fmt.Println("Checkpoint-routeAmount", routeAmount)
// fmt.Println("Checkpoint-requestIdentifier", requestIdentifier)
// fmt.Println("Checkpoint-requestTimestamp", requestTimestamp)
// fmt.Println("Checkpoint-msg.SrcChainId", msg.SrcChainId)
// fmt.Println("Checkpoint-routeRecipient", routeRecipient)
// fmt.Println("Checkpoint-msg.DestChainId", msg.DestChainId)
// fmt.Println("Checkpoint-asmAddress", asmAddress)
// fmt.Println("Checkpoint-msg.RequestSender", msg.RequestSender)
// fmt.Println("Checkpoint-handler", handler)
// fmt.Println("Checkpoint-Payload", requestPacket.Payload)
// fmt.Println("Checkpoint-abiEncodedBatch", abiEncodedBatch)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if err != nil {
panic(fmt.Sprintf("Error packing checkpoint! %s/n", err))
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you were to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
return crypto.Keccak256Hash(abiEncodedBatch[4:]).Bytes()
}
func (msg CrosschainRequest) GetNearCheckpoint(routerIDstring string) []byte {
//////////////////////////////////////////////////////////////////////
///// Build data with types required for iReceive gateway call /////
//////////////////////////////////////////////////////////////////////
metadata := DecodeEvmContractMetadata(&msg)
requestPacket := DecodeRouterCrosschainPacket(&msg)
methodNameBytes := []uint8("iReceive")
var crosschainMethodName [32]uint8
copy(crosschainMethodName[:], methodNameBytes)
routeAmount := msg.RouteAmount.BigInt()
requestIdentifier := &big.Int{}
requestIdentifier.SetUint64(msg.RequestIdentifier)
requestTimestamp := &big.Int{}
requestTimestamp.SetUint64(uint64(msg.SrcTimestamp))
routeRecipient := msg.RouteRecipient
asmAddress := metadata.AsmAddress
handler := requestPacket.Handler
/////////////////////////////////////////////////
///// pack abi for iReceive function //////////
/////////////////////////////////////////////////
abiDef, err := abi.JSON(strings.NewReader(util.CrosschainRequestNearCheckpointABIJSON))
if err != nil {
panic("Bad ABI constant!")
}
// the methodName needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
abiEncodedBatch, err := abiDef.Pack("checkpoint",
crosschainMethodName,
routeAmount,
requestIdentifier,
requestTimestamp,
msg.SrcChainId,
routeRecipient,
msg.DestChainId,
asmAddress,
msg.RequestSender,
handler,
requestPacket.Payload,
metadata.IsReadCall,
)
// fmt.Println("Checkpoint- crosschainMethodName ", crosschainMethodName)
// fmt.Println("Checkpoint-routeAmount", routeAmount)
// fmt.Println("Checkpoint-requestIdentifier", requestIdentifier)
// fmt.Println("Checkpoint-requestTimestamp", requestTimestamp)
// fmt.Println("Checkpoint-msg.SrcChainId", msg.SrcChainId)
// fmt.Println("Checkpoint-routeRecipient", routeRecipient)
// fmt.Println("Checkpoint-msg.DestChainId", msg.DestChainId)
// fmt.Println("Checkpoint-asmAddress", asmAddress)
// fmt.Println("Checkpoint-msg.RequestSender", msg.RequestSender)
// fmt.Println("Checkpoint-handler", handler)
// fmt.Println("Checkpoint-Payload", requestPacket.Payload)
// fmt.Println("Checkpoint-abiEncodedBatch", abiEncodedBatch)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if err != nil {
panic(fmt.Sprintf("Error packing checkpoint! %s/n", err))
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you were to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
return crypto.Keccak256Hash(abiEncodedBatch[4:]).Bytes()
}
func (msg CrosschainRequest) GetEvmCheckpoint(routerIDstring string) []byte {
//////////////////////////////////////////////////////////////////////
///// Build data with types required for iReceive gateway call /////
//////////////////////////////////////////////////////////////////////
metadata := DecodeEvmContractMetadata(&msg)
requestPacket := DecodeRouterCrosschainPacket(&msg)
methodNameBytes := []uint8("iReceive")
var crosschainMethodName [32]uint8
copy(crosschainMethodName[:], methodNameBytes)
routeAmount := msg.RouteAmount.BigInt()
requestIdentifier := &big.Int{}
requestIdentifier.SetUint64(msg.RequestIdentifier)
requestTimestamp := &big.Int{}
requestTimestamp.SetUint64(uint64(msg.SrcTimestamp))
routeRecipient := common.HexToAddress(msg.RouteRecipient)
asmAddress := common.HexToAddress(metadata.AsmAddress)
handler := common.HexToAddress(requestPacket.Handler)
/////////////////////////////////////////////////
///// pack abi for iReceive function //////////
/////////////////////////////////////////////////
abiDef, err := abi.JSON(strings.NewReader(util.CrosschainRequestCheckpointABIJSON))
if err != nil {
panic("Bad ABI constant!")
}
// the methodName needs to be the same as the 'name' above in the checkpointAbiJson
// but other than that it's a constant that has no impact on the output. This is because
// it gets encoded as a function name which we must then discard.
abiEncodedBatch, err := abiDef.Pack("checkpoint",
crosschainMethodName,
routeAmount,
requestIdentifier,
requestTimestamp,
msg.SrcChainId,
routeRecipient,
msg.DestChainId,
asmAddress,
msg.RequestSender,
handler,
requestPacket.Payload,
metadata.IsReadCall,
)
// fmt.Println("Checkpoint- crosschainMethodName ", crosschainMethodName)
// fmt.Println("Checkpoint-routeAmount", routeAmount)
// fmt.Println("Checkpoint-requestIdentifier", requestIdentifier)
// fmt.Println("Checkpoint-requestTimestamp", requestTimestamp)
// fmt.Println("Checkpoint-msg.SrcChainId", msg.SrcChainId)
// fmt.Println("Checkpoint-routeRecipient", routeRecipient)
// fmt.Println("Checkpoint-msg.DestChainId", msg.DestChainId)
// fmt.Println("Checkpoint-asmAddress", asmAddress)
// fmt.Println("Checkpoint-msg.RequestSender", msg.RequestSender)
// fmt.Println("Checkpoint-handler", handler)
// fmt.Println("Checkpoint-Payload", requestPacket.Payload)
// fmt.Println("Checkpoint-abiEncodedBatch", abiEncodedBatch)
// this should never happen outside of test since any case that could crash on encoding
// should be filtered above.
if err != nil {
panic(fmt.Sprintf("Error packing checkpoint! %s/n", err))
}
// we hash the resulting encoded bytes discarding the first 4 bytes these 4 bytes are the constant
// method name 'checkpoint'. If you were to replace the checkpoint constant in this code you would
// then need to adjust how many bytes you truncate off the front to get the output of abi.encode()
return crypto.Keccak256Hash(abiEncodedBatch[4:]).Bytes()
}
func (msg CrosschainRequest) GetStarknetCheckpoint(routerIDstring string) []byte {
fmt.Println("Inside GetStarknetCheckpoint", "reqIdentifier", msg.RequestIdentifier)
//SrcChainId
srcChainId, err := utils.HexToFelt(msg.SrcChainId)
if err != nil {
fmt.Println(err)
}
//routeRecipient
var routeRecipient *felt.Felt
if msg.RouteRecipient == "" {
// If RouteRecipient is empty, set it to 0x0
var err error
routeRecipient, err = utils.HexToFelt("0x0")
if err != nil {
fmt.Println("Error setting routeRecipient to 0x0:", err)
}
} else {
// Convert msg.RouteRecipient to felt
var err error
routeRecipient, err = utils.HexToFelt(msg.RouteRecipient)
if err != nil {
fmt.Println("Error converting routeRecipient:", err)
}
}
//routeAmount
routeAmount := BigIntToFeltParts_newarray(msg.RouteAmount.BigInt())
requestTimestamp := &big.Int{}
requestTimestamp.SetUint64(uint64(msg.SrcTimestamp))
//requestTimestamp
requestTimestamp_ := BigIntToFeltParts_newarray(requestTimestamp)
metadata := DecodeEvmContractMetadata(&msg)
//AsmAddress
asmAddress, err := utils.HexToFelt(metadata.AsmAddress)
if err != nil {
fmt.Println(err)
}
//DestchainId
destChainId, err := utils.HexToFelt(msg.DestChainId)
if err != nil {
fmt.Println(err)
}
//RequestSender
requestSender_arr := splitStringIntoHalves(msg.RequestSender)
requestSender_felt, err := utils.HexArrToFelt(requestSender_arr)
if err != nil {
fmt.Println(err)
}
requestPacket := DecodeRouterCrosschainPacket(&msg)
//HandlerAddress
handler_address, err := utils.HexToFelt(requestPacket.Handler)
if err != nil {
fmt.Println(err)
}
//Packet
processed_packet, err := processHexStrings(bytesToHexStrings(requestPacket.Payload))
if err != nil {
fmt.Println(err)
}
packet_felt, err := utils.HexArrToFelt(processed_packet)
if err != nil {
fmt.Println(err)
}
//IsReadCall
isReadCall, err := utils.HexToFelt(boolToHex(metadata.IsReadCall))
if err != nil {
fmt.Println(err)
}
requestIdentifier := &big.Int{}
requestIdentifier.SetUint64(msg.RequestIdentifier)
requestIdentifier_felt := BigIntToFeltParts_newarray(requestIdentifier)
// Run through the elements of the batch and serialize them
method_name := "0x695265636569766500000000000000"
method_name_felt, err := utils.HexToFelt(method_name)
if err != nil {
fmt.Println(err)
}
var serialized_data []*felt.Felt
empty_string := "0x0"
empty_string_felt, err := utils.HexToFelt(empty_string)
if err != nil {
fmt.Println(err)
}
serialized_data = append(serialized_data, empty_string_felt)
serialized_data = append(serialized_data, method_name_felt)
serialized_data = append(serialized_data, routeAmount...)
serialized_data = append(serialized_data, requestIdentifier_felt...)
serialized_data = append(serialized_data, requestTimestamp_...)
serialized_data = append(serialized_data, srcChainId)
serialized_data = append(serialized_data, routeRecipient)
serialized_data = append(serialized_data, destChainId)
serialized_data = append(serialized_data, asmAddress)
serialized_data = generic_append(requestSender_felt, serialized_data)
serialized_data = append(serialized_data, handler_address)
serialized_data = generic_append(packet_felt, serialized_data)
serialized_data = append(serialized_data, isReadCall)
new_big_int := utils.FeltArrToBigIntArr(serialized_data)
hashed_val, err := hashSlice(new_big_int)
if err != nil {
fmt.Println(err)
}
ensure_bytes := Ensure32Bytes(hashed_val)
return ensure_bytes
}
func hashSlice(input []*big.Int) (*big.Int, error) {
// Check if the input slice is empty and return an error or a specific hash value
if len(input) == 0 {
return nil, fmt.Errorf("input slice is empty")
}
// Initialize hash with the first element, if specific initialization is needed, adjust accordingly
hash, _ := starknetgo.Curve.PedersenHash([]*big.Int{big.NewInt(int64(0)), input[0]})
// Start from the second element since we used the first element to initialize the hash
for _, val := range input[1:] {
// Use the current hash and the next element to compute the new hash
newHash, err := starknetgo.Curve.PedersenHash([]*big.Int{hash, val})
if err != nil {
return nil, fmt.Errorf("error computing PedersenHash: %w", err)
}
fmt.Println("New Hash : ", newHash)
hash = newHash // Update hash with the new hash value for the next iteration
}
hash, _ = starknetgo.Curve.PedersenHash([]*big.Int{hash, big.NewInt(int64(112))})
hash, _ = starknetgo.Curve.PedersenHash([]*big.Int{hash, big.NewInt(int64(11))})
fmt.Println("Final Hash : ", hash)
return hash, nil
}
func generic_append(val []*felt.Felt, to_append []*felt.Felt) []*felt.Felt {
size := utils.Uint64ToFelt(uint64(len(val)))
to_append = append(to_append, size)
to_append = append(to_append, val...)
return to_append
}
func processHexStrings(hexStrings []string) ([]string, error) {
var processedStrings []string
for _, hexStr := range hexStrings {
// Check if the string starts with 0x and has a valid digit as the next character
if strings.HasPrefix(hexStr, "0x") && len(hexStr) > 2 && hexStr[2] >= '1' && hexStr[2] <= '9' {
// Remove the 0x prefix to simplify processing
trimmedStr := hexStr[2:]
// Find the index of the first occurrence of 00
zeroIndex := strings.Index(trimmedStr, "00")
if zeroIndex == -1 {
// If 00 is not found, append the original string
processedStrings = append(processedStrings, hexStr)
} else {
// Extract the substring up to and including the first occurrence of 00 and prepend 0x
result := "0x" + trimmedStr[:zeroIndex+2]
processedStrings = append(processedStrings, result)
}
} else {
// If the string does not meet the criteria, append it as is
processedStrings = append(processedStrings, hexStr)
}
}
return processedStrings, nil
}
func bytesToHexStrings(bytes []byte) []string {
var result []string
for len(bytes) > 0 {
// Take the first 32 bytes as a chunk
chunkSize := 32
if len(bytes) < chunkSize {
chunkSize = len(bytes)
}
// Convert the chunk to a hexadecimal string
hexStr := hex.EncodeToString(bytes[:chunkSize])
// Append the hex string to the result
result = append(result, "0x"+hexStr)
// Remove the processed bytes from concatenatedBytes
bytes = bytes[chunkSize:]
}
return result
}
func splitStringIntoHalves(input string) []string {
length := len(input)
// Calculate the midpoint index
midpoint := length / 2
// Split the string into two halves
firstHalf := input[:midpoint]
secondHalf := input[midpoint:]
// Create a string slice to store the halves
halves := []string{firstHalf, secondHalf}
return halves
}
func BigIntToFeltParts_newarray(val *big.Int) []*felt.Felt {
var feltArr []*felt.Felt
lowHex, highHex := BigIntToHexU128Parts(val)
low_hex, _ := utils.HexToFelt(lowHex)
high_hex, _ := utils.HexToFelt(highHex)
feltArr = append(feltArr, low_hex)
feltArr = append(feltArr, high_hex)
return feltArr
}
func BigIntToHexU128Parts(num *big.Int) (lowHex, highHex string) {
// Create a big.Int with a value of 2^128
u128 := new(big.Int)
u128.Exp(big.NewInt(2), big.NewInt(128), nil)
// Calculate the low part
low := new(big.Int).And(num, new(big.Int).Sub(u128, big.NewInt(1)))
lowHex = fmt.Sprintf("0x%032x", low)
// Calculate the high part
high := new(big.Int).Rsh(num, 128)
highHex = fmt.Sprintf("0x%04x", high)
return lowHex, highHex
}
func boolToHex(b bool) string {
if b {
return "0x01"
}
return "0x00"
}