-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathxrpl.go
362 lines (305 loc) · 10.5 KB
/
xrpl.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
package integrationtests
import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"fmt"
mathrand "math/rand"
"strings"
"sync"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/pkg/errors"
rippledata "github.com/rubblelabs/ripple/data"
"github.com/samber/lo"
"github.com/stretchr/testify/require"
"github.com/CoreumFoundation/coreum-tools/pkg/http"
"github.com/CoreumFoundation/coreum-tools/pkg/retry"
coreumapp "github.com/CoreumFoundation/coreum/v4/app"
coreumconfig "github.com/CoreumFoundation/coreum/v4/pkg/config"
coreumkeyring "github.com/CoreumFoundation/coreum/v4/pkg/keyring"
"github.com/CoreumFoundation/coreumbridge-xrpl/relayer/logger"
"github.com/CoreumFoundation/coreumbridge-xrpl/relayer/xrpl"
)
const (
// XRPCurrencyCode is XRP toke currency code on XRPL chain.
XRPCurrencyCode = "XRP"
ecdsaKeyType = rippledata.ECDSA
faucetKeyringKeyName = "faucet"
)
// ********** XRPLChain **********
// XRPLChainConfig is a config required for the XRPL chain to be created.
type XRPLChainConfig struct {
RPCAddress string
FundingSeed string
}
// XRPLChain is XRPL chain for the testing.
type XRPLChain struct {
cfg XRPLChainConfig
signer *xrpl.KeyringTxSigner
rpcClient *xrpl.RPCClient
fundMu *sync.Mutex
}
// NewXRPLChain returns the new instance of the XRPL chain.
func NewXRPLChain(cfg XRPLChainConfig, log logger.Logger) (XRPLChain, error) {
kr := createInMemoryKeyring()
faucetPrivateKey, err := extractPrivateKeyFromSeed(cfg.FundingSeed)
if err != nil {
return XRPLChain{}, err
}
if err := kr.ImportPrivKeyHex(faucetKeyringKeyName, faucetPrivateKey, string(hd.Secp256k1Type)); err != nil {
return XRPLChain{}, errors.Wrapf(err, "failed to import private key to keyring")
}
rpcClient := xrpl.NewRPCClient(
xrpl.DefaultRPCClientConfig(cfg.RPCAddress),
log,
http.NewRetryableClient(http.DefaultClientConfig()),
nil,
)
signer := xrpl.NewKeyringTxSigner(kr)
return XRPLChain{
cfg: cfg,
signer: signer,
rpcClient: rpcClient,
fundMu: &sync.Mutex{},
}, nil
}
// Config returns the chain config.
func (c XRPLChain) Config() XRPLChainConfig {
return c.cfg
}
// RPCClient returns the XRPL RPC client.
func (c XRPLChain) RPCClient() *xrpl.RPCClient {
return c.rpcClient
}
// GenAccount generates the active signer with the initial provided amount.
func (c XRPLChain) GenAccount(ctx context.Context, t *testing.T, amount float64) rippledata.Account {
t.Helper()
acc := c.GenEmptyAccount(t)
c.CreateAccount(ctx, t, acc, amount)
return acc
}
// GenEmptyAccount generates the signer but doesn't activate it.
func (c XRPLChain) GenEmptyAccount(t *testing.T) rippledata.Account {
t.Helper()
const signerKeyName = "signer"
kr := createInMemoryKeyring()
_, mnemonic, err := kr.NewMnemonic(
signerKeyName,
keyring.English,
xrpl.XRPLHDPath,
"",
hd.Secp256k1,
)
require.NoError(t, err)
acc, err := xrpl.NewKeyringTxSigner(kr).Account(signerKeyName)
require.NoError(t, err)
// reimport with the key as signer address
_, err = c.signer.GetKeyring().NewAccount(
acc.String(),
mnemonic,
"",
xrpl.XRPLHDPath,
hd.Secp256k1,
)
require.NoError(t, err)
return acc
}
// CreateAccount funds the provided account with the amount/reserve to activate the account.
func (c XRPLChain) CreateAccount(ctx context.Context, t *testing.T, acc rippledata.Account, amount float64) {
t.Helper()
// amount to activate the account and some tokens on top
c.FundAccount(ctx, t, acc, amount+xrpl.ReserveToActivateAccount)
}
// GetSignerKeyring returns signer keyring.
func (c XRPLChain) GetSignerKeyring() keyring.Keyring {
return c.signer.GetKeyring()
}
// GetSignerPubKey returns signer public key.
func (c XRPLChain) GetSignerPubKey(t *testing.T, acc rippledata.Account) rippledata.PublicKey {
pubKey, err := c.signer.PubKey(acc.String())
require.NoError(t, err)
return pubKey
}
// ActivateAccount funds the provided account with the amount required for the activation.
func (c XRPLChain) ActivateAccount(ctx context.Context, t *testing.T, acc rippledata.Account) {
t.Helper()
c.FundAccount(ctx, t, acc, xrpl.ReserveToActivateAccount)
}
// FundAccountForTicketAllocation funds the provided account with the amount required for the ticket allocation.
func (c XRPLChain) FundAccountForTicketAllocation(
ctx context.Context, t *testing.T, acc rippledata.Account, ticketsNumber uint32,
) {
c.FundAccount(ctx, t, acc, xrpl.ReservePerItem*float64(ticketsNumber))
}
// FundAccountForSignerListSet funds the provided account with the amount required for the multi-signing set.
// Multi-signing set is a single ledger object so one reserve is needed.
func (c XRPLChain) FundAccountForSignerListSet(
ctx context.Context, t *testing.T, acc rippledata.Account,
) {
c.FundAccount(ctx, t, acc, xrpl.ReservePerItem)
}
// FundAccount funds the provided account with the provided amount.
func (c XRPLChain) FundAccount(ctx context.Context, t *testing.T, acc rippledata.Account, amount float64) {
t.Helper()
c.fundMu.Lock()
defer c.fundMu.Unlock()
xrpAmount, err := rippledata.NewAmount(fmt.Sprintf("%f%s", amount, XRPCurrencyCode))
require.NoError(t, err)
fundXrpTx := rippledata.Payment{
Destination: acc,
Amount: *xrpAmount,
TxBase: rippledata.TxBase{
TransactionType: rippledata.PAYMENT,
},
}
fundingAcc, err := c.signer.Account(faucetKeyringKeyName)
require.NoError(t, err)
c.AutoFillTx(ctx, t, &fundXrpTx, fundingAcc)
require.NoError(t, c.signer.Sign(&fundXrpTx, faucetKeyringKeyName))
//t.Logf("Funding account, account address: %s, amount: %f", acc, amount)
require.NoError(t, c.RPCClient().SubmitAndAwaitSuccess(ctx, &fundXrpTx))
//t.Logf("The account %s is funded", acc)
}
// AutoFillSignAndSubmitTx autofills the transaction and submits it.
func (c XRPLChain) AutoFillSignAndSubmitTx(
ctx context.Context, t *testing.T, tx rippledata.Transaction, acc rippledata.Account,
) error {
t.Helper()
c.AutoFillTx(ctx, t, tx, acc)
return c.SignAndSubmitTx(ctx, t, tx, acc)
}
// Multisign signs the transaction for the multi-signing.
func (c XRPLChain) Multisign(t *testing.T, tx rippledata.MultiSignable, acc rippledata.Account) rippledata.Signer {
t.Helper()
txSigner, err := c.signer.MultiSign(tx, acc.String())
require.NoError(t, err)
return txSigner
}
// SignAndSubmitTx signs the transaction from the signer and submits it.
func (c XRPLChain) SignAndSubmitTx(
ctx context.Context, t *testing.T, tx rippledata.Transaction, acc rippledata.Account,
) error {
t.Helper()
require.NoError(t, c.signer.Sign(tx, acc.String()))
return c.RPCClient().SubmitAndAwaitSuccess(ctx, tx)
}
// AutoFillTx add seq number and fee for the transaction.
func (c XRPLChain) AutoFillTx(
ctx context.Context,
t *testing.T,
tx rippledata.Transaction,
sender rippledata.Account,
) {
t.Helper()
require.NoError(t, c.rpcClient.AutoFillTx(ctx, tx, sender, xrpl.MaxAllowedXRPLSigners))
}
// GetAccountBalance returns account balance for the provided issuer and currency.
func (c XRPLChain) GetAccountBalance(
ctx context.Context, t *testing.T, account, issuer rippledata.Account, currency rippledata.Currency,
) rippledata.Amount {
balance, ok := c.GetAccountBalances(ctx, t, account)[fmt.Sprintf("%s/%s",
xrpl.ConvertCurrencyToString(currency), issuer.String())]
if !ok {
// equal to zero
return rippledata.Amount{
Value: &rippledata.Value{},
Currency: currency,
Issuer: issuer,
}
}
return balance
}
// GetAccountBalances returns account balances.
func (c XRPLChain) GetAccountBalances(
ctx context.Context, t *testing.T, acc rippledata.Account,
) map[string]rippledata.Amount {
t.Helper()
balances, err := c.rpcClient.GetXRPLBalances(ctx, acc)
require.NoError(t, err)
return lo.SliceToMap(balances, func(amt rippledata.Amount) (string, rippledata.Amount) {
return fmt.Sprintf("%s/%s", xrpl.ConvertCurrencyToString(amt.Currency), amt.Issuer.String()), amt
})
}
// AwaitLedger awaits for ledger index.
func (c XRPLChain) AwaitLedger(ctx context.Context, t *testing.T, ledgerIndex int64) {
t.Helper()
t.Logf("Waiting for the ledger:%d", ledgerIndex)
retryCtx, retryCtxCancel := context.WithTimeout(ctx, time.Minute)
defer retryCtxCancel()
require.NoError(t, retry.Do(retryCtx, 250*time.Millisecond, func() error {
reqCtx, reqCtxCancel := context.WithTimeout(retryCtx, 3*time.Second)
defer reqCtxCancel()
res, err := c.rpcClient.LedgerCurrent(reqCtx)
if err != nil {
return retry.Retryable(err)
}
if res.LedgerCurrentIndex < ledgerIndex {
return retry.Retryable(errors.Errorf(
"ledger has not passed, current:%d, expected:%d",
res.LedgerCurrentIndex,
ledgerIndex,
))
}
return nil
}))
}
func extractPrivateKeyFromSeed(seedPhrase string) (string, error) {
seed, err := rippledata.NewSeedFromAddress(seedPhrase)
if err != nil {
return "", errors.Wrapf(err, "failed to create rippledata seed from seed phrase")
}
key := seed.Key(ecdsaKeyType)
return hex.EncodeToString(key.Private(lo.ToPtr(uint32(0)))), nil
}
func createInMemoryKeyring() keyring.Keyring {
encodingConfig := coreumconfig.NewEncodingConfig(coreumapp.ModuleBasics)
return coreumkeyring.NewConcurrentSafeKeyring(keyring.NewInMemory(encodingConfig.Codec))
}
// ExtractTicketsFromMeta extracts tickets info from the tx metadata.
func ExtractTicketsFromMeta(txRes xrpl.TxResult) []*rippledata.Ticket {
createdTickets := make([]*rippledata.Ticket, 0)
for _, node := range txRes.MetaData.AffectedNodes {
createdNode := node.CreatedNode
if createdNode == nil {
continue
}
newFields := createdNode.NewFields
if newFields == nil {
continue
}
if rippledata.TICKET.String() != newFields.GetType() {
continue
}
ticket, ok := newFields.(*rippledata.Ticket)
if !ok {
continue
}
createdTickets = append(createdTickets, ticket)
}
return createdTickets
}
// GenerateXRPLCurrency generates random XRPL currency.
func GenerateXRPLCurrency(t *testing.T) rippledata.Currency {
// from 3 to 20 symbols
currencyString := lo.RandomString(
mathrand.Intn(20-4)+3, []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"),
)
if len(currencyString) != 3 {
currencyString = hex.EncodeToString([]byte(currencyString))
currencyString += strings.Repeat("0", 40-len(currencyString))
}
currency, err := rippledata.NewCurrency(currencyString)
require.NoError(t, err)
return currency
}
// GenXRPLTxHash generates random XRPL tx hash.
func GenXRPLTxHash(t *testing.T) string {
t.Helper()
hash := rippledata.Hash256{}
_, err := cryptorand.Read(hash[:])
require.NoError(t, err)
return strings.ToUpper(hash.String())
}