Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
434 changes: 427 additions & 7 deletions solana/call_test.go

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions solana/computer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ func TestFailedPostprocessCompaction(t *testing.T) {
main, err := node.store.ReadSystemCallByRequestId(ctx, main.RequestId, common.RequestStateFailed)
require.Nil(err)
require.NotNil(main)
outputs, _, err := node.GetSystemCallReferenceOutputs(ctx, user.UserId, main.RequestHash, common.RequestStateDone)
outputs, err := node.getLockedSystemCallOutputs(ctx, main, common.RequestStateDone)
require.Nil(err)
require.Len(outputs, 2)
sub, err := node.store.ReadSystemCallByRequestId(ctx, postId, common.RequestStatePending)
Expand Down Expand Up @@ -410,7 +410,7 @@ func TestFailedPostprocessCompaction(t *testing.T) {
require.Nil(err)
require.NotNil(main)
require.Len(main.GetRefundIds(), 1)
outputs, _, err := node.GetSystemCallReferenceOutputs(ctx, user.UserId, main.RequestHash, common.RequestStateDone)
outputs, err := node.getLockedSystemCallOutputs(ctx, main, common.RequestStateDone)
require.Nil(err)
require.Len(outputs, 2)
ar, handled, err := node.store.ReadActionResult(ctx, out.OutputId, out.OutputId)
Expand Down Expand Up @@ -675,7 +675,7 @@ func testUserRequestSystemCall(ctx context.Context, require *require.Assertions,
require.Equal(hex.EncodeToString(user.FingerprintWithPath()), call.Public)
require.False(call.Signature.Valid)
require.True(call.RequestSignerAt.Valid)
os, _, err := node.GetSystemCallReferenceOutputs(ctx, user.UserId, call.RequestHash, common.RequestStatePending)
os, err := node.getLockedSystemCallOutputs(ctx, call, common.RequestStatePending)
require.Nil(err)
require.Len(os, 2)
}
Expand Down
83 changes: 78 additions & 5 deletions solana/deposit_scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/MixinNetwork/safe/mtg"
bin "github.com/gagliardetto/binary"
"github.com/gagliardetto/solana-go"
"github.com/gagliardetto/solana-go/programs/system"
"github.com/gagliardetto/solana-go/programs/token"
"github.com/gagliardetto/solana-go/rpc"
"github.com/stretchr/testify/require"
Expand All @@ -38,6 +39,78 @@ func TestDepositScannerNonceExhaustion(t *testing.T) {
testDepositScannerMint(t, solana.MPK(solanaApp.WrappedSolanaAddress), solanaApp.SolanaDecimal, false, true)
}

func TestNativeSOLDepositAmounts(t *testing.T) {
ctx := common.EnableTestEnvironment(t.Context())
st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "sol-deposit.sqlite"))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, st.Close()) })
payer := solana.NewWallet()
sender, user, group := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey()
master := hex.EncodeToString(group.Bytes())
require.NoError(t, st.TestWriteKey(ctx, "group-key", master, nil, true))
req := &store.Request{
Id: "sol-deposit-user", Role: RequestRoleUser, Action: OperationTypeAddUser,
State: common.RequestStateInitial, CreatedAt: time.Now().UTC(), Output: &mtg.Action{},
}
req.Output.OutputId = req.Id
require.NoError(t, st.WriteRequestIfNotExist(ctx, req))
require.NoError(t, st.WriteUserWithRequest(ctx, req, store.StartUserId.String(), "sol-deposit-mix", user.String(), master))
node := &Node{store: st, conf: &Configuration{SolanaKey: payer.PrivateKey.String(), SolanaDepositEntry: group.String()}}

for index, test := range []struct {
name string
amounts []uint64
balance uint64
want uint64
}{
{name: "single eligible transfer", amounts: []uint64{solanaCleanupDustLamports}, balance: solanaCleanupRentLamports + solanaCleanupDustLamports, want: solanaCleanupDustLamports},
{name: "small and large transfers", amounts: []uint64{50_000, 3_000_000}, balance: 3_050_000, want: 3_050_000},
{name: "split transfers reach minimum", amounts: []uint64{60_000, 40_000}, balance: solanaCleanupRentLamports + 100_000, want: 100_000},
{name: "combined amount is dust", amounts: []uint64{60_000, 39_999}, balance: solanaCleanupRentLamports + 99_999},
{name: "combined transfer leaves insufficient rent", amounts: []uint64{60_000, 40_000}, balance: solanaCleanupRentLamports + 99_999},
{name: "incoming amount already spent", amounts: []uint64{3_000_000}, balance: solanaCleanupRentLamports},
} {
t.Run(test.name, func(t *testing.T) {
var instructions []solana.Instruction
for _, amount := range test.amounts {
instructions = append(instructions, system.NewTransferInstruction(amount, sender, user).Build())
}
source, err := solana.NewTransaction(instructions, solana.Hash{}, solana.TransactionPayer(sender))
require.NoError(t, err)
signature := solana.Signature{byte(index + 1)}
source.Signatures = []solana.Signature{signature}
meta := &rpc.TransactionMeta{PostBalances: make([]uint64, len(source.Message.AccountKeys))}
for i, account := range source.Message.AccountKeys {
if account == user {
meta.PostBalances[i] = test.balance
break
}
}
result, err := json.Marshal(map[string]any{"transaction": []string{source.MustToBase64(), "base64"}, "meta": meta})
require.NoError(t, err)
require.NoError(t, st.WriteCache(ctx, "getTransaction:"+signature.String(), hex.EncodeToString(result)))

incoming, err := solanaApp.ExtractTransfersFromTransaction(ctx, source, meta, nil)
require.NoError(t, err)
transfers, err := node.buildSolanaDepositTransfers(ctx, source, meta, incoming)
require.NoError(t, err)
proposal := []solana.Instruction{solana.NewInstruction(solana.MemoProgramID, nil, []byte("deposit fixture"))}
if test.want == 0 {
require.Empty(t, transfers)
} else {
require.Len(t, transfers[user.String()], 1)
sweep := transfers[user.String()][0]
require.Equal(t, test.want, sweep.Amount)
require.Equal(t, solanaApp.SolanaChainBase, sweep.AssetId)
proposal = append(proposal, system.NewTransferInstruction(sweep.Amount, user, sweep.Destination).Build())
}
cleanup, err := solana.NewTransaction(proposal, solana.Hash{}, solana.TransactionPayer(payer.PublicKey()))
require.NoError(t, err)
require.NoError(t, node.compareDepositCallWithSolanaTx(ctx, cleanup, signature.String(), user.String()))
})
}
}

func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8, missing, waitForNonce bool) {
t.Helper()
ctx := common.EnableTestEnvironment(context.Background())
Expand Down Expand Up @@ -157,7 +230,7 @@ func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8,
if waitForNonce {
require.NoError(t, node.writeBlockCheckpoint(ctx, 99))
for range 2 {
err := node.solanaReadBlocks(ctx, 99, 101, 2_039_280)
err := node.solanaReadBlocks(ctx, 99, 101)
require.ErrorIs(t, err, store.ErrNoSpareNonceAccount)
checkpoint, err := st.ReadProperty(ctx, store.SolanaScanHeightKey)
require.NoError(t, err)
Expand All @@ -172,7 +245,7 @@ func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8,
nonce := solana.NewWallet().PublicKey()
require.NoError(t, st.WriteNonceAccount(ctx, nonce.String(), solana.Hash{}.String()))

require.NoError(t, node.solanaReadBlocks(ctx, 99, 101, 2_039_280))
require.NoError(t, node.solanaReadBlocks(ctx, 99, 101))
checkpoint, err := st.ReadProperty(ctx, store.SolanaScanHeightKey)
require.NoError(t, err)
require.Equal(t, "101", checkpoint)
Expand Down Expand Up @@ -220,7 +293,7 @@ func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8,
require.NoError(t, err)
require.True(t, reserved.CallId.Valid)
// Re-reading a processed block must not create a second deposit call.
require.NoError(t, node.solanaReadBlock(ctx, 100, 2_039_280))
require.NoError(t, node.solanaReadBlock(ctx, 100))
require.Empty(t, network.mtgChannel(node.id))

// An unfinished block can be retried after one of its deposits has
Expand All @@ -231,7 +304,7 @@ func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8,
State: common.RequestStateDone, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
}))
require.NoError(t, st.UpdateNonceAccount(ctx, nonce.String(), solana.Hash{1}.String(), reserved.CallId.String))
require.NoError(t, node.solanaProcessTransaction(ctx, tx, meta, 2_039_280))
require.NoError(t, node.solanaProcessTransaction(ctx, tx, meta))
spare, err := st.CountSpareNonceAccounts(ctx)
require.NoError(t, err)
require.Equal(t, 1, spare)
Expand All @@ -241,7 +314,7 @@ func testDepositScannerMint(t *testing.T, mint solana.PublicKey, decimals uint8,
// Missing mint data must fail the block on every attempt, without caching
// the absence or marking the deposit's block as successfully processed.
for range 2 {
err := node.solanaReadBlock(ctx, 100, 2_039_280)
err := node.solanaReadBlock(ctx, 100)
require.ErrorIs(t, err, rpc.ErrNotFound)
require.ErrorContains(t, err, mint.String())
require.ErrorContains(t, err, tx.Signatures[0].String())
Expand Down
130 changes: 92 additions & 38 deletions solana/mvm.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/MixinNetwork/safe/common"
"github.com/MixinNetwork/safe/mtg"
"github.com/gagliardetto/solana-go"
"github.com/gagliardetto/solana-go/programs/token"
"github.com/gagliardetto/solana-go/rpc"
"github.com/gofrs/uuid/v5"
"github.com/shopspring/decimal"
Expand Down Expand Up @@ -342,8 +343,8 @@ func (node *Node) processConfirmNonce(ctx context.Context, req *store.Request) (
if err != nil {
panic(err)
}
os, _, err := node.GetSystemCallReferenceOutputs(ctx, call.UserIdFromPublicPath(), call.RequestHash, byte(outputState))
logger.Printf("node.GetSystemCallReferenceTxs(%s) => %v %v", req.MixinHash.String(), os, err)
os, err := node.getLockedSystemCallOutputs(ctx, call, byte(outputState))
logger.Printf("node.getLockedSystemCallOutputs(%s) => %v %v", call.RequestId, os, err)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -702,25 +703,21 @@ func (node *Node) processConfirmCall(ctx context.Context, req *store.Request) ([
}

// For situation 1, 4
return node.confirmMainOrPrepareSystemCalls(ctx, req, calls, storage)
return node.confirmMainOrPrepareSystemCalls(ctx, req, calls, storage, transactions[len(transactions)-1])
}

func (node *Node) confirmMainOrPrepareSystemCalls(ctx context.Context, req *store.Request, calls []*store.SystemCall, storage []byte) ([]*mtg.Transaction, string) {
func (node *Node) confirmMainOrPrepareSystemCalls(ctx context.Context, req *store.Request, calls []*store.SystemCall, storage []byte, mainResult *rpc.GetTransactionResult) ([]*mtg.Transaction, string) {
call := calls[len(calls)-1]

var session *store.Session
var outputs []*store.UserOutput
var post *store.SystemCall
if call.Type != store.CallTypeMain {
return node.failRequest(ctx, req, "")
}
os, _, err := node.GetSystemCallReferenceOutputs(ctx, call.UserIdFromPublicPath(), call.RequestHash, common.RequestStatePending)
outputs, err := node.getLockedSystemCallOutputs(ctx, call, common.RequestStatePending)
if err != nil {
panic(err)
}
outputs = os

post, err = node.getPostProcessCall(ctx, req, FlagConfirmCallSuccess, call, storage)
post, err := node.getPostProcessCall(ctx, req, call, storage, mainResult, outputs)
logger.Printf("node.getPostProcessCall(%v %v) => %v %v", req, call, post, err)
if err != nil {
return node.failRequest(ctx, req, "")
Expand Down Expand Up @@ -1114,15 +1111,15 @@ func (node *Node) failSystemCall(ctx context.Context, req *store.Request, call *
}
}

os, _, err := node.GetSystemCallReferenceOutputs(ctx, main.UserIdFromPublicPath(), main.RequestHash, systemCallReferenceOutputStateValue(referenceCall.State))
os, err := node.getLockedSystemCallOutputs(ctx, main, systemCallReferenceOutputStateValue(referenceCall.State))
if err != nil {
panic(err)
}
outputs = os
}

var session *store.Session
post, err := node.getPostProcessCall(ctx, req, FlagConfirmCallFail, referenceCall, storage)
post, err := node.getPostProcessCall(ctx, req, referenceCall, storage, nil, nil)
logger.Printf("node.getPostProcessCall(%v %v) => %v %v", req, call, post, err)
if err != nil {
return node.failRequest(ctx, req, "")
Expand Down Expand Up @@ -1246,6 +1243,41 @@ func (node *Node) validateConfirmCall(ctx context.Context, req *store.Request, s
return call, transaction, nil
}

type burnAssetAmount struct {
asset *solanaApp.DeployedAsset
amount decimal.Decimal
}

// Deposit and post-process calls validate a single user's burn authority before
// signing. Keep mint order stable so every node constructs payments in the same order.
func (node *Node) burnAssetAmounts(ctx context.Context, burns []*token.BurnChecked) ([]burnAssetAmount, error) {
var totals []burnAssetAmount
indexes := make(map[string]int)
for _, burn := range burns {
if *burn.Amount == 0 {
continue
}
address := burn.GetMintAccount().PublicKey.String()
index, exists := indexes[address]
if !exists {
asset, err := node.store.ReadDeployedAssetByAddress(ctx, address)
if err != nil {
return nil, err
}
if asset == nil {
return nil, fmt.Errorf("undeployed burn mint: %s", address)
}
index = len(totals)
indexes[address] = index
totals = append(totals, burnAssetAmount{asset: asset, amount: decimal.Zero})
}
total := &totals[index]
amount := decimal.NewFromUint64(*burn.Amount).Shift(-int32(total.asset.Decimals))
total.amount = total.amount.Add(amount)
}
return totals, nil
}

func (node *Node) confirmBurnRelatedSystemCall(ctx context.Context, req *store.Request, call *store.SystemCall, rpcTx *rpc.GetTransactionResult, signature string) ([]*mtg.Transaction, string) {
main := call
if call.Superior != call.RequestId {
Expand Down Expand Up @@ -1273,31 +1305,39 @@ func (node *Node) confirmBurnRelatedSystemCall(ctx context.Context, req *store.R
user.ChainAddress = "5YLSixqjK2m8ECirGaco8tHSn2Uc4aY7cLPoMSMptsgG"
}
}
changes := node.buildUserBalanceChangesFromMeta(ctx, tx, rpcTx.Meta, solana.MPK(user.ChainAddress))
err = node.processTransactionWithAddressLookups(ctx, tx)
if err != nil {
panic(err)
}
changes, err := buildUserBalanceChangesFromMeta(tx, rpcTx.Meta, solana.MPK(user.ChainAddress))
if err != nil {
logger.Printf("burn settlement %s: %v", signature, err)
return node.failRequest(ctx, req, "")
}

totals, err := node.burnAssetAmounts(ctx, solanaApp.ExtractBurnsFromTransaction(ctx, tx))
if err != nil {
logger.Printf("burn settlement %s: %v", signature, err)
return node.failRequest(ctx, req, "")
}
for _, total := range totals {
change := changes[total.asset.Address]
if change == nil || !change.Amount.Neg().Equal(total.amount) {
logger.Printf("burn settlement %s: mint %s burned %s with balance change %v", signature, total.asset.Address, total.amount, change)
// Fail only this confirmation request. The observer can retry the
// pending call with the same confirmed Solana transaction.
return node.failRequest(ctx, req, "")
}
}

var txs []*mtg.Transaction
var ids []string
bs := solanaApp.ExtractBurnsFromTransaction(ctx, tx)
for _, burn := range bs {
address := burn.GetMintAccount().PublicKey.String()
da, err := node.store.ReadDeployedAssetByAddress(ctx, address)
if err != nil || da == nil {
panic(err)
}

amount := decimal.New(int64(*burn.Amount), -int32(da.Decimals))
amt := mc.NewIntegerFromString(amount.String())
for _, total := range totals {
da := total.asset
amt := mc.NewIntegerFromString(total.amount.String())
if common.CheckTestEnvironment(ctx) && req.Id == "329346e1-34c2-4de0-8e35-729518eda8bd" {
amt = mc.NewIntegerFromString("0.02")
}
if amt.Sign() == 0 {
continue
}

change := changes[address]
if change == nil || !change.Amount.Abs().Equal(amount) {
continue
}

id := common.UniqueId(signature, fmt.Sprintf("BURN:%s", da.AssetId))
id = common.UniqueId(id, user.MixAddress)
Expand All @@ -1318,17 +1358,31 @@ func (node *Node) confirmBurnRelatedSystemCall(ctx context.Context, req *store.R
ids = append(ids, tx.TraceId)
}

fd, err := node.store.ReadFailedDepositByHash(ctx, signature)
deposits, err := node.store.ListUnconfirmedDepositsByHash(ctx, signature)
if err != nil {
panic(err)
}
if fd != nil {
id := common.UniqueId(fd.Hash, fmt.Sprint(fd.Index))
// One payment per asset lets all of its deposits draw from the same
// Mixin inputs, which cannot be reused by a second payment in this action.
depositAmounts := make(map[string]decimal.Decimal, len(deposits))
for _, deposit := range deposits {
depositAmounts[deposit.AssetId] = depositAmounts[deposit.AssetId].Add(decimal.RequireFromString(deposit.Amount))
}
for _, deposit := range deposits {
amount, exists := depositAmounts[deposit.AssetId]
if !exists {
continue
}
delete(depositAmounts, deposit.AssetId)

// In index order, the first deposit provides the payment trace. A
// single deposit keeps the same trace as the normal deposit path.
id := common.UniqueId(deposit.Hash, fmt.Sprint(deposit.Index))
id = common.UniqueId(id, node.SolanaDepositEntry().String())
memo := []byte(fd.Hash)
tx := node.buildTransaction(ctx, req.Output, node.conf.AppId, fd.AssetId, mix.Members(), int(mix.Threshold), fd.Amount, memo, id)
memo := []byte(deposit.Hash)
tx := node.buildTransaction(ctx, req.Output, node.conf.AppId, deposit.AssetId, mix.Members(), int(mix.Threshold), amount.String(), memo, id)
if tx == nil {
return node.failRequest(ctx, req, fd.AssetId)
return node.failRequest(ctx, req, deposit.AssetId)
}
txs = append(txs, tx)
ids = append(ids, tx.TraceId)
Expand All @@ -1338,7 +1392,7 @@ func (node *Node) confirmBurnRelatedSystemCall(ctx context.Context, req *store.R
old = append(old, ids...)
call.RefundTraces = sql.NullString{Valid: true, String: strings.Join(old, ",")}

err = node.store.ConfirmBurnRelatedSystemCallWithRequest(ctx, req, call, fd, txs)
err = node.store.ConfirmBurnRelatedSystemCallWithRequest(ctx, req, call, deposits, txs)
if err != nil {
panic(err)
}
Expand Down
Loading
Loading