diff --git a/apps/solana/common.go b/apps/solana/common.go index c269efc..246a8e0 100644 --- a/apps/solana/common.go +++ b/apps/solana/common.go @@ -195,6 +195,21 @@ type Transfer struct { MayClosedWsolAta *solana.PublicKey } +type InitialAssetMovementKind string + +const ( + InitialAssetMovementTransfer InitialAssetMovementKind = "transfer" + InitialAssetMovementBurn InitialAssetMovementKind = "burn" +) + +type InitialAssetMovement struct { + Kind InitialAssetMovementKind + TokenAddress string + Sender string + Value *big.Int + Decimal uint8 +} + type LookupTableStats struct { Table string Space uint @@ -218,6 +233,59 @@ func FindAssociatedTokenAddress( return addr } +func ExtractInitialAssetMovements(tx *solana.Transaction) []*InitialAssetMovement { + var movements []*InitialAssetMovement + for _, ix := range tx.Message.Instructions { + programKey, err := tx.Message.Program(ix.ProgramIDIndex) + if err != nil { + panic(err) + } + + accounts, err := ix.ResolveInstructionAccounts(&tx.Message) + if err != nil { + panic(err) + } + + switch programKey { + case system.ProgramID: + transfer, ok := DecodeSystemTransfer(accounts, ix.Data) + if ok { + movements = append(movements, &InitialAssetMovement{ + Kind: InitialAssetMovementTransfer, + TokenAddress: SolanaEmptyAddress, + Sender: transfer.GetFundingAccount().PublicKey.String(), + Value: new(big.Int).SetUint64(*transfer.Lamports), + Decimal: SolanaDecimal, + }) + } + case solana.TokenProgramID, solana.Token2022ProgramID: + transfer, ok := DecodeTokenTransferChecked(accounts, ix.Data) + if ok { + movements = append(movements, &InitialAssetMovement{ + Kind: InitialAssetMovementTransfer, + TokenAddress: transfer.GetMintAccount().PublicKey.String(), + Sender: transfer.GetOwnerAccount().PublicKey.String(), + Value: new(big.Int).SetUint64(*transfer.Amount), + Decimal: *transfer.Decimals, + }) + continue + } + + burn, ok := DecodeTokenBurn(accounts, ix.Data) + if ok { + movements = append(movements, &InitialAssetMovement{ + Kind: InitialAssetMovementBurn, + TokenAddress: burn.GetMintAccount().PublicKey.String(), + Sender: burn.GetOwnerAccount().PublicKey.String(), + Value: new(big.Int).SetUint64(*burn.Amount), + Decimal: *burn.Decimals, + }) + } + } + } + return movements +} + func BuildSignersGetter(keys ...solana.PrivateKey) func(key solana.PublicKey) *solana.PrivateKey { mapKeys := make(map[solana.PublicKey]*solana.PrivateKey) for _, k := range keys { diff --git a/solana/call_test.go b/solana/call_test.go new file mode 100644 index 0000000..37afac3 --- /dev/null +++ b/solana/call_test.go @@ -0,0 +1,572 @@ +package solana + +import ( + "context" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "math/big" + "path/filepath" + "testing" + "time" + + "github.com/MixinNetwork/bot-api-go-client/v3" + solanaApp "github.com/MixinNetwork/computer/apps/solana" + "github.com/MixinNetwork/computer/store" + "github.com/MixinNetwork/mixin/crypto" + "github.com/MixinNetwork/safe/common" + "github.com/MixinNetwork/safe/mtg" + "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/gofrs/uuid/v5" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/require" +) + +func TestUserSystemCallFeePayer(t *testing.T) { + ctx := context.Background() + payer := solana.NewWallet() + user, nonce, recipient := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey() + node := &Node{conf: &Configuration{SolanaKey: payer.PrivateKey.String()}} + for _, test := range []struct { + name string + feePayer solana.PublicKey + wantErr string + }{ + {name: "node pays fees", feePayer: payer.PublicKey()}, + {name: "user pays fees despite node signing", feePayer: user, wantErr: "invalid system call fee payer"}, + } { + t.Run(test.name, func(t *testing.T) { + tx, err := solana.NewTransaction([]solana.Instruction{ + system.NewAdvanceNonceAccountInstruction(nonce, solana.SysVarRecentBlockHashesPubkey, payer.PublicKey()).Build(), + system.NewTransferInstruction(1, user, recipient).Build(), + }, solana.Hash{}, solana.TransactionPayer(test.feePayer)) + require.NoError(t, err) + // Both transactions satisfy the previous signer-only check. + require.True(t, tx.IsSigner(payer.PublicKey())) + err = node.checkUserSystemCall(ctx, tx) + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + } else { + require.NoError(t, err) + } + }) + } + require.ErrorContains(t, node.checkUserSystemCall(ctx, new(solana.Transaction)), "invalid system call fee payer") +} + +func TestSOLCleanupPolicy(t *testing.T) { + require.True(t, isSOLCleanupDust(solanaApp.SolanaChainBase, decimal.NewFromInt(99_999))) + require.False(t, isSOLCleanupDust(solanaApp.SolanaChainBase, decimal.NewFromInt(100_000))) + require.False(t, isSOLCleanupDust("other-asset", decimal.NewFromInt(1))) + for _, test := range []struct { + name string + balance uint64 + amount uint64 + unsafe bool + wantErr bool + }{ + {name: "leave exactly rent", balance: 950_240, amount: 300_000}, + {name: "leave below rent", balance: 950_239, amount: 300_000, unsafe: true}, + {name: "close account", balance: 300_000, amount: 300_000}, + {name: "overdraw", balance: 300_000, amount: 300_001, wantErr: true}, + } { + t.Run(test.name, func(t *testing.T) { + unsafe, err := isSOLCleanupRentUnsafe(test.balance, test.amount) + require.Equal(t, test.unsafe, unsafe) + require.Equal(t, test.wantErr, err != nil) + }) + } +} + +func TestCompareSOLCleanupMovements(t *testing.T) { + for _, test := range []struct { + name string + balance uint64 + expected uint64 + actual uint64 + present bool + wantErr string + }{ + {name: "omit below dust", balance: 1_000_000, expected: 99_999}, + {name: "require exact dust", balance: 1_000_000, expected: 100_000, wantErr: "missing transfer"}, + {name: "accept exact dust", balance: 1_000_000, expected: 100_000, actual: 100_000, present: true}, + {name: "require below former rent threshold", balance: 1_000_000, expected: 300_000, wantErr: "missing transfer"}, + {name: "accept below former rent threshold", balance: 1_000_000, expected: 300_000, actual: 300_000, present: true}, + {name: "omit rent unsafe transfer", balance: 1_000_000, expected: 800_000}, + {name: "reject rent unsafe transfer", balance: 1_000_000, expected: 800_000, actual: 800_000, present: true, wantErr: "insufficient rent"}, + {name: "accept zero remainder", balance: 1_000_000, expected: 1_000_000, actual: 1_000_000, present: true}, + {name: "require zero remainder transfer", balance: 1_000_000, expected: 1_000_000, wantErr: "missing transfer"}, + {name: "accept rent boundary", balance: 950_240, expected: 300_000, actual: 300_000, present: true}, + {name: "reject wrong amount below dust", balance: 1_000_000, expected: 50_000, actual: 50_001, present: true, wantErr: "invalid transfer"}, + {name: "reject rent unsafe below dust", balance: 650_240, expected: 50_000, actual: 50_000, present: true, wantErr: "insufficient rent"}, + {name: "reject zero expectation bypass", balance: 1_000_000, expected: 0, actual: 100_000, present: true, wantErr: "unexpected SOL cleanup"}, + {name: "reject overdrawn expectation", balance: 1_000_000, expected: 1_000_001, wantErr: "exceeds balance"}, + } { + t.Run(test.name, func(t *testing.T) { + expected := map[string]*ReferencedTxAsset{ + solanaApp.SolanaEmptyAddress: { + Solana: true, AssetId: solanaApp.SolanaChainBase, Address: solanaApp.SolanaEmptyAddress, + Decimal: solanaApp.SolanaDecimal, Amount: decimal.NewFromUint64(test.expected).Shift(-solanaApp.SolanaDecimal), + }, + } + actual := make(map[string]*solanaApp.InitialAssetMovement) + if test.present { + actual[solanaApp.SolanaEmptyAddress] = &solanaApp.InitialAssetMovement{ + Kind: solanaApp.InitialAssetMovementTransfer, TokenAddress: solanaApp.SolanaEmptyAddress, + Value: new(big.Int).SetUint64(test.actual), Decimal: solanaApp.SolanaDecimal, + } + } + err := new(Node).comparePostProcessMovements(context.Background(), solanaApp.InitialAssetMovementTransfer, expected, actual, &test.balance) + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestSOLCleanupOmissionStillRequiresToken(t *testing.T) { + ctx := context.Background() + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "cleanup.sqlite")) + require.NoError(t, err) + defer st.Close() + mint := solana.NewWallet().PublicKey().String() + // A non-NFT mint lookup with no external RPC dependency. + require.NoError(t, st.WriteCache(ctx, "getAccount:"+mint, hex.EncodeToString([]byte(`{"value":{"data":["","base64"]}}`)))) + node := &Node{store: st} + expected := map[string]*ReferencedTxAsset{ + solanaApp.SolanaEmptyAddress: {AssetId: solanaApp.SolanaChainBase, Decimal: 9, Amount: decimal.RequireFromString("0.0008")}, + mint: {Decimal: 6, Amount: decimal.NewFromInt(1)}, + } + balance := uint64(1_000_000) + require.ErrorContains(t, node.comparePostProcessMovements(ctx, solanaApp.InitialAssetMovementTransfer, expected, nil, &balance), "missing transfer") + actual := map[string]*solanaApp.InitialAssetMovement{ + mint: {Kind: solanaApp.InitialAssetMovementTransfer, TokenAddress: mint, Decimal: 6, Value: big.NewInt(1_000_000)}, + } + require.NoError(t, node.comparePostProcessMovements(ctx, solanaApp.InitialAssetMovementTransfer, expected, actual, &balance)) +} + +func TestCleanupSOLBalanceSnapshot(t *testing.T) { + ctx := context.Background() + payer := solana.NewWallet().PublicKey() + source := solana.NewWallet().PublicKey() + tx, err := solana.NewTransaction([]solana.Instruction{ + system.NewTransferInstruction(1, source, payer).Build(), + }, solana.Hash{}, solana.TransactionPayer(payer)) + require.NoError(t, err) + accounts, err := tx.AccountMetaList() + require.NoError(t, err) + meta := &rpc.TransactionMeta{PostBalances: make([]uint64, len(accounts))} + for index, account := range accounts { + if account.PublicKey == source { + meta.PostBalances[index] = 1_000_000 + } + } + node := new(Node) + balance, err := node.cleanupSOLBalance(ctx, nil, tx, meta, source) + require.NoError(t, err) + require.NotNil(t, balance) + require.EqualValues(t, 1_000_000, *balance) + absent, err := node.cleanupSOLBalance(ctx, nil, tx, meta, solana.NewWallet().PublicKey()) + require.NoError(t, err) + require.Nil(t, absent) + zero, err := node.cleanupSOLBalance(ctx, nil, tx, &rpc.TransactionMeta{PostBalances: make([]uint64, len(accounts))}, source) + require.NoError(t, err) + require.NotNil(t, zero) + require.Zero(t, *zero) + _, err = node.cleanupSOLBalance(ctx, nil, tx, &rpc.TransactionMeta{}, source) + require.ErrorContains(t, err, "missing cleanup source balance") + _, err = node.cleanupSOLBalance(ctx, nil, nil, nil, source) + require.ErrorContains(t, err, "missing confirmed cleanup transaction") + + // Failed cleanup/refund builders load the pinned confirmation from cache, + // rather than querying the source's current account balance. + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "cleanup.sqlite")) + require.NoError(t, err) + defer st.Close() + node.store = st + raw, err := tx.MarshalBinary() + require.NoError(t, err) + result, err := json.Marshal(map[string]any{ + "meta": meta, "transaction": []string{base64.StdEncoding.EncodeToString(raw), "base64"}, + }) + require.NoError(t, err) + require.NoError(t, st.WriteCache(ctx, "getTransaction:confirmed-attempt", hex.EncodeToString(result))) + call := &store.SystemCall{Hash: sql.NullString{Valid: true, String: "confirmed-attempt"}} + balance, err = node.cleanupSOLBalance(ctx, call, nil, nil, source) + require.NoError(t, err) + require.NotNil(t, balance) + require.EqualValues(t, 1_000_000, *balance) +} + +func TestSOLConfirmationFixture(t *testing.T) { + ctx := context.Background() + require := require.New(t) + payer := solana.NewWallet() + source := solana.NewWallet().PublicKey() + var nodes []*Node + for i := 0; i < 2; i++ { + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "confirmation.sqlite")) + require.NoError(err) + defer st.Close() + nodes = append(nodes, &Node{store: st, conf: &Configuration{SolanaKey: payer.PrivateKey.String()}}) + } + for index, signature := range []solana.Signature{ + solana.MustSignatureFromBase58("42fwVqHYmfLqoqQ3XgELu72FL6t2Q2HCqY7XzkVCdVsWHGoT6DHBk7qzoUkpfjqs42ygSSnFWzarQZdpUX9tLK6r"), + solana.MustSignatureFromBase58("sKxPceKjZb4PiywqwMP3Wyf9YoPqdgZZ5MLNxkpRv7qgTXVxK8UQRGkjMT47qJht5muuUPpqynkrM5C6BcYSELg"), + } { + failed := index == 1 + call := &store.SystemCall{Hash: sql.NullString{Valid: true, String: signature.String()}} + testCacheSOLConfirmation(ctx, require, nodes, signature, source, 1_000_000_000, failed) + for _, node := range nodes { + // No RPC client is configured: all nodes must use the same fixture. + result, err := node.RPCGetTransaction(ctx, signature.String()) + require.NoError(err) + require.Equal(failed, result.Meta.Err != nil) + tx, err := result.Transaction.GetTransaction() + require.NoError(err) + require.Equal(signature, tx.Signatures[0]) + balance, err := node.cleanupSOLBalance(ctx, call, nil, nil, source) + require.NoError(err) + require.NotNil(balance) + require.EqualValues(1_000_000_000, *balance) + changes := node.buildUserBalanceChangesFromMeta(ctx, tx, result.Meta, source) + require.True(changes[solanaApp.SolanaEmptyAddress].Amount.IsZero()) + } + } +} + +// Exercise receiver filtering, ledger selection, instruction extraction and both +// comparison passes together. Account fixtures keep all cases independent of RPC. +func TestDepositCallMovements(t *testing.T) { + ctx := context.Background() + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "deposit.sqlite")) + require.NoError(t, err) + defer st.Close() + node := &Node{store: st} + payer := solana.NewWallet().PublicKey() + user, other, entry := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey() + mint, deployed, unexpected, nft := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey() + for _, address := range []solana.PublicKey{mint, deployed, unexpected} { + require.NoError(t, st.WriteCache(ctx, "getAccount:"+address.String(), hex.EncodeToString([]byte(`{"value":{"data":["","base64"]}}`)))) + } + // Standard initialized NFT mint: supply 1 and decimals 0. + nftData := make([]byte, 82) + nftData[36], nftData[45] = 1, 1 + account, err := json.Marshal(map[string]any{"value": map[string]any{"data": []string{base64.StdEncoding.EncodeToString(nftData), "base64"}}}) + require.NoError(t, err) + require.NoError(t, st.WriteCache(ctx, "getAccount:"+nft.String(), hex.EncodeToString(account))) + // Persist deployment through the store API, as production classification does. + req := &store.Request{Id: "deposit-movement-fixture", Role: RequestRoleObserver, 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.WriteDeployedAssetsWithRequest(ctx, req, []*solanaApp.DeployedAsset{{AssetId: "external-asset", ChainId: "external-chain", Address: deployed.String(), Decimals: 6}})) + changes := func(receiver solana.PublicKey, address solana.PublicKey, amount int64) map[string]*big.Int { + return map[string]*big.Int{receiver.String() + ":" + address.String(): big.NewInt(amount)} + } + for _, program := range []solana.PublicKey{solana.TokenProgramID, solana.Token2022ProgramID} { + t.Run(program.String(), func(t *testing.T) { + movement := func(burn bool, address, owner solana.PublicKey, amount uint64) solana.Instruction { + ata := solanaApp.FindAssociatedTokenAddress(owner, address, program) + decimals := uint8(6) + if address == nft { + decimals = 0 + } + var ix solana.Instruction + if burn { + ix = token.NewBurnCheckedInstruction(amount, decimals, ata, address, owner, nil).Build() + } else { + ix = token.NewTransferCheckedInstruction(amount, decimals, ata, address, solanaApp.FindAssociatedTokenAddress(entry, address, program), owner, nil).Build() + } + data, err := ix.Data() + require.NoError(t, err) + return solana.NewInstruction(program, ix.Accounts(), data) + } + multiReceiver := changes(user, mint, 1_000_000) + multiReceiver[other.String()+":"+mint.String()] = big.NewInt(7_000_000) + // No account fixture for this address: filtering must happen before lookup. + multiReceiver[other.String()+":"+solana.NewWallet().PublicKey().String()] = big.NewInt(1_000_000) + mixed := changes(user, mint, 1_000_000) + mixed[user.String()+":"+deployed.String()] = big.NewInt(2_000_000) + for _, test := range []struct { + name string + expected map[string]*big.Int + instructions []solana.Instruction + wantErr string + }{ + {name: "multiple receivers", expected: multiReceiver, instructions: []solana.Instruction{movement(false, mint, user, 1_000_000)}}, + {name: "ignore another sender", expected: multiReceiver, instructions: []solana.Instruction{movement(false, mint, user, 1_000_000), movement(false, mint, other, 7_000_000)}}, + {name: "aggregate split transfers", expected: changes(user, mint, 1_000_000), instructions: []solana.Instruction{movement(false, mint, user, 400_000), movement(false, mint, user, 600_000)}}, + {name: "external asset burn", expected: changes(user, deployed, 1_000_000), instructions: []solana.Instruction{movement(true, deployed, user, 1_000_000)}}, + {name: "transfer and burn different assets", expected: mixed, instructions: []solana.Instruction{movement(false, mint, user, 1_000_000), movement(true, deployed, user, 2_000_000)}}, + {name: "missing transfer", expected: changes(user, mint, 1_000_000), wantErr: "non-existed transfer deposit"}, + {name: "missing burn", expected: changes(user, deployed, 1_000_000), wantErr: "non-existed burn deposit"}, + {name: "wrong transfer amount", expected: changes(user, mint, 1_000_000), instructions: []solana.Instruction{movement(false, mint, user, 999_999)}, wantErr: "invalid transfer deposit"}, + {name: "wrong burn amount", expected: changes(user, deployed, 1_000_000), instructions: []solana.Instruction{movement(true, deployed, user, 999_999)}, wantErr: "invalid burn deposit"}, + {name: "unexpected transfer", instructions: []solana.Instruction{movement(false, unexpected, user, 1_000_000)}, wantErr: "unexpected transfer deposit"}, + {name: "unexpected burn", instructions: []solana.Instruction{movement(true, unexpected, user, 1_000_000)}, wantErr: "unexpected burn deposit"}, + {name: "transfer cannot replace external burn", expected: changes(user, deployed, 1_000_000), instructions: []solana.Instruction{movement(false, deployed, user, 1_000_000)}, wantErr: "unexpected transfer deposit"}, + {name: "burn cannot replace native transfer", expected: changes(user, mint, 1_000_000), instructions: []solana.Instruction{movement(true, mint, user, 1_000_000)}, wantErr: "non-existed transfer deposit"}, + {name: "split burn and transfer cannot satisfy burn", expected: changes(user, deployed, 1_000_000), instructions: []solana.Instruction{movement(true, deployed, user, 600_000), movement(false, deployed, user, 400_000)}, wantErr: "unexpected transfer deposit"}, + {name: "omit SOL dust", expected: changes(user, solana.PublicKey{}, 9)}, + {name: "SOL threshold requires transfer", expected: changes(user, solana.PublicKey{}, 10), wantErr: "non-existed transfer deposit"}, + {name: "accept SOL threshold", expected: changes(user, solana.PublicKey{}, 10), instructions: []solana.Instruction{system.NewTransferInstruction(10, user, entry).Build()}}, + {name: "unexpected SOL dust exempt", instructions: []solana.Instruction{system.NewTransferInstruction(9, user, entry).Build()}}, + {name: "unexpected SOL threshold rejected", instructions: []solana.Instruction{system.NewTransferInstruction(10, user, entry).Build()}, wantErr: "unexpected transfer deposit"}, + {name: "omit NFT", expected: changes(user, nft, 1)}, + {name: "NFT transfer exempt", expected: changes(user, nft, 1), instructions: []solana.Instruction{movement(false, nft, user, 1)}}, + {name: "NFT burn exempt", expected: changes(user, nft, 1), instructions: []solana.Instruction{movement(true, nft, user, 1)}}, + } { + t.Run(test.name, func(t *testing.T) { + instructions := append([]solana.Instruction{solana.NewInstruction(solana.MemoProgramID, nil, []byte("deposit"))}, test.instructions...) + tx, err := solana.NewTransaction(instructions, solana.Hash{}, solana.TransactionPayer(payer)) + require.NoError(t, err) + tx.Signatures = make([]solana.Signature, tx.Message.Header.NumRequiredSignatures) + expectedTransfers, expectedBurns := node.collectExpectedDepositMovements(ctx, test.expected, user.String()) + actualTransfers, actualBurns, err := buildInitialAssetMovementMaps(tx, user.String(), "") + require.NoError(t, err) + err = node.compareDepositMovements(ctx, "deposit-fixture", tx, solanaApp.InitialAssetMovementTransfer, expectedTransfers, actualTransfers) + if err == nil { + err = node.compareDepositMovements(ctx, "deposit-fixture", tx, solanaApp.InitialAssetMovementBurn, expectedBurns, actualBurns) + } + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + } else { + require.NoError(t, err) + } + }) + } + }) + } +} + +func TestPrepareCallMovements(t *testing.T) { + payer := solana.NewWallet() + mtg, user, other, mint, nonce := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey() + node := &Node{conf: &Configuration{SolanaKey: payer.PrivateKey.String()}} + solAsset := &ReferencedTxAsset{Solana: true, AssetId: solanaApp.SolanaChainBase, ChainId: solanaApp.SolanaChainBase, Address: solanaApp.SolanaEmptyAddress, Decimal: 9, Amount: decimal.RequireFromString("0.001")} + feeAsset := *solAsset + feeAsset.Fee = true + tokenAsset := &ReferencedTxAsset{Solana: true, AssetId: "native-token", ChainId: solanaApp.SolanaChainBase, Address: mint.String(), Decimal: 6, Amount: decimal.NewFromInt(1)} + mintAsset := *tokenAsset + mintAsset.Solana = false + for _, program := range []solana.PublicKey{solana.TokenProgramID, solana.Token2022ProgramID} { + t.Run(program.String(), func(t *testing.T) { + wrap := func(ix solana.Instruction) solana.Instruction { + data, err := ix.Data() + require.NoError(t, err) + return solana.NewInstruction(program, ix.Accounts(), data) + } + transfer := func(amount uint64, owner, receiver solana.PublicKey) solana.Instruction { + return wrap(token.NewTransferCheckedInstruction(amount, 6, solanaApp.FindAssociatedTokenAddress(owner, mint, program), mint, solanaApp.FindAssociatedTokenAddress(receiver, mint, program), owner, nil).Build()) + } + mintTo := func(amount uint64, receiver solana.PublicKey) solana.Instruction { + return wrap(token.NewMintToInstruction(amount, mint, solanaApp.FindAssociatedTokenAddress(receiver, mint, program), mtg, nil).Build()) + } + for _, test := range []struct { + name string + assets []*ReferencedTxAsset + instructions []solana.Instruction + allowPayerFee bool + wantErr string + }{ + {name: "SOL transfer", assets: []*ReferencedTxAsset{solAsset}, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, mtg, user).Build()}}, + {name: "token transfer", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{transfer(1_000_000, mtg, user)}}, + {name: "external mint", assets: []*ReferencedTxAsset{&mintAsset}, instructions: []solana.Instruction{mintTo(1_000_000, user)}}, + {name: "mixed SOL and token", assets: []*ReferencedTxAsset{solAsset, tokenAsset}, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, mtg, user).Build(), transfer(1_000_000, mtg, user)}}, + {name: "aggregate split transfers", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{transfer(400_000, mtg, user), transfer(600_000, mtg, user)}}, + {name: "aggregate references", assets: []*ReferencedTxAsset{tokenAsset, tokenAsset}, instructions: []solana.Instruction{transfer(2_000_000, mtg, user)}}, + {name: "wrong SOL recipient", assets: []*ReferencedTxAsset{solAsset}, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, mtg, other).Build()}, wantErr: "invalid prepare SOL recipient"}, + {name: "wrong SOL source", assets: []*ReferencedTxAsset{solAsset}, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, other, user).Build()}, wantErr: "unexpected prepare asset movement"}, + {name: "wrong token recipient", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{transfer(1_000_000, mtg, other)}, wantErr: "invalid prepare token recipient"}, + {name: "wrong token owner", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{transfer(1_000_000, other, user)}, wantErr: "unexpected prepare asset movement"}, + {name: "wrong mint recipient", assets: []*ReferencedTxAsset{&mintAsset}, instructions: []solana.Instruction{mintTo(1_000_000, other)}, wantErr: "invalid prepare mint recipient"}, + {name: "wrong amount", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{transfer(999_999, mtg, user)}, wantErr: "invalid prepare asset amount"}, + {name: "missing movement", assets: []*ReferencedTxAsset{tokenAsset}, wantErr: "missing prepare asset movement"}, + {name: "unexpected movement", instructions: []solana.Instruction{transfer(1_000_000, mtg, user)}, wantErr: "unexpected prepare asset movement"}, + {name: "transfer cannot replace mint", assets: []*ReferencedTxAsset{&mintAsset}, instructions: []solana.Instruction{transfer(1_000_000, mtg, user)}, wantErr: "unexpected prepare asset movement"}, + {name: "mint cannot replace transfer", assets: []*ReferencedTxAsset{tokenAsset}, instructions: []solana.Instruction{mintTo(1_000_000, user)}, wantErr: "unexpected prepare asset movement"}, + {name: "disallowed program", instructions: []solana.Instruction{solana.NewInstruction(other, nil, nil)}, wantErr: "program:"}, + {name: "known payer fee", assets: []*ReferencedTxAsset{&feeAsset}, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, payer.PublicKey(), user).Build()}}, + {name: "unknown payer fee allowed", allowPayerFee: true, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, payer.PublicKey(), user).Build()}}, + {name: "unknown payer fee rejected", instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, payer.PublicKey(), user).Build()}, wantErr: "unexpected prepare asset movement"}, + {name: "fee exception still checks recipient", allowPayerFee: true, instructions: []solana.Instruction{system.NewTransferInstruction(1_000_000, payer.PublicKey(), other).Build()}, wantErr: "invalid prepare SOL recipient"}, + } { + t.Run(test.name, func(t *testing.T) { + instructions := append([]solana.Instruction{system.NewAdvanceNonceAccountInstruction(nonce, solana.SysVarRecentBlockHashesPubkey, payer.PublicKey()).Build()}, test.instructions...) + tx, err := solana.NewTransaction(instructions, solana.Hash{}, solana.TransactionPayer(payer.PublicKey())) + require.NoError(t, err) + err = node.comparePrepareCallWithSolanaTx(tx, test.assets, mtg, user, test.allowPayerFee) + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + } else { + require.NoError(t, err) + } + }) + } + }) + } +} + +// Movement comparison does not check mint authorities; the envelope must reject +// an unrelated signing authority before a Prepare can be accepted. +func TestPrepareCallAuthority(t *testing.T) { + payer := solana.NewWallet() + mtg, user, other, mint, nonce := solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey(), solana.NewWallet().PublicKey() + node := &Node{conf: &Configuration{SolanaKey: payer.PrivateKey.String()}} + for _, program := range []solana.PublicKey{solana.TokenProgramID, solana.Token2022ProgramID} { + for _, authority := range []solana.PublicKey{mtg, other} { + t.Run(program.String()+"/"+authority.String(), func(t *testing.T) { + ix := token.NewMintToInstruction(1_000_000, mint, solanaApp.FindAssociatedTokenAddress(user, mint, program), authority, nil).Build() + data, err := ix.Data() + require.NoError(t, err) + tx, err := solana.NewTransaction([]solana.Instruction{system.NewAdvanceNonceAccountInstruction(nonce, solana.SysVarRecentBlockHashesPubkey, payer.PublicKey()).Build(), solana.NewInstruction(program, ix.Accounts(), data)}, solana.Hash{}, solana.TransactionPayer(payer.PublicKey())) + require.NoError(t, err) + err = node.VerifySubSystemCallEnvelope(tx, mtg, false) + if authority == other { + require.ErrorContains(t, err, "invalid subsystem signers") + return + } + require.NoError(t, err) + require.NoError(t, node.VerifySubSystemCall(context.Background(), tx, other, user)) + require.NoError(t, node.comparePrepareCallWithSolanaTx(tx, []*ReferencedTxAsset{{Address: mint.String(), Decimal: 6, Amount: decimal.NewFromInt(1)}}, mtg, user, false)) + }) + } + } +} + +func TestSystemCallAssetPrecision(t *testing.T) { + for _, test := range []struct { + name, chain string + precision int + amounts []string + wantErr bool + }{ + {name: "exact token unit", chain: solanaApp.SolanaChainBase, precision: 6, amounts: []string{"0.000001"}}, + {name: "truncates to zero", chain: solanaApp.SolanaChainBase, precision: 6, amounts: []string{"0.00000001"}, wantErr: true}, + {name: "positive amount loses remainder", chain: solanaApp.SolanaChainBase, precision: 6, amounts: []string{"1.00000001"}, wantErr: true}, + {name: "aggregate before checking", chain: solanaApp.SolanaChainBase, precision: 6, amounts: []string{"0.00000050", "0.00000050"}}, + {name: "aggregate still loses remainder", chain: solanaApp.SolanaChainBase, precision: 6, amounts: []string{"0.00000050", "0.00000049"}, wantErr: true}, + {name: "SOL nine decimals", chain: solanaApp.SolanaChainBase, precision: 9, amounts: []string{"0.00000001"}}, + {name: "whole unit mint rejects fraction", chain: solanaApp.SolanaChainBase, precision: 0, amounts: []string{"1.99"}, wantErr: true}, + {name: "deployed uses eight decimals", chain: common.SafeEthereumChainId, precision: 18, amounts: []string{"0.00000001"}}, + {name: "deployed ignores original lower precision", chain: common.SafeLitecoinChainId, precision: 2, amounts: []string{"1.12345678"}}, + {name: "deployed rejects over eight decimals", chain: common.SafeEthereumChainId, precision: 18, amounts: []string{"1.000000001"}, wantErr: true}, + } { + t.Run(test.name, func(t *testing.T) { + var outputs []*store.UserOutput + for _, amount := range test.amounts { + outputs = append(outputs, &store.UserOutput{AssetId: "asset", ChainId: test.chain, Amount: amount, Asset: bot.AssetNetwork{ChainID: test.chain, Precision: test.precision}}) + } + err := validateSystemCallAssetAmounts(outputs) + if test.wantErr { + require.ErrorContains(t, err, "unrepresentable system call asset amount") + } else { + require.NoError(t, err) + } + for i, output := range outputs { + require.Equal(t, test.amounts[i], output.Amount) + } + }) + } +} + +func TestSystemCallPrecisionRefundsAllDeposits(t *testing.T) { + for _, test := range []struct { + name string + amounts [2]string + refund string + }{ + {name: "zero units", amounts: [2]string{"0.00000001", "0.00000002"}, refund: "0.00000003"}, + {name: "nonzero amount loses remainder", amounts: [2]string{"0.5", "0.50000001"}, refund: "1.00000001"}, + } { + t.Run(test.name, func(t *testing.T) { + ctx := common.EnableTestEnvironment(context.Background()) + node, md := testBuildNode(ctx, require.New(t), t.TempDir(), 0) + defer node.store.Close() + defer md.Close() + mix := bot.NewUUIDMixAddress([]string{"a7376114-5db3-4822-bd3c-26416b57da1b"}, 1) + userID := store.StartUserId.String() + invalidID, validID := "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222" + deposit := func(assetID, amount string, precision int) *store.UserOutput { + id := uuid.Must(uuid.NewV4()).String() + hash := crypto.Sha256Hash([]byte(id)) + req := &store.Request{Id: id, MixinHash: hash, AssetId: assetID, Amount: decimal.RequireFromString(amount), Role: RequestRoleUser, Action: OperationTypeUserDeposit, State: common.RequestStateInitial, CreatedAt: time.Now().UTC(), Output: &mtg.Action{}} + req.Output.OutputId = id + require.NoError(t, node.store.WriteRequestIfNotExist(ctx, req)) + output := &store.UserOutput{OutputId: id, UserId: userID, TransactionHash: hash.String(), AssetId: assetID, ChainId: solanaApp.SolanaChainBase, Amount: amount, State: common.RequestStateInitial, CreatedAt: req.CreatedAt, UpdatedAt: req.CreatedAt, Asset: bot.AssetNetwork{ChainID: solanaApp.SolanaChainBase, Precision: precision}} + require.NoError(t, node.store.WriteUserDepositWithRequest(ctx, req, output)) + return output + } + outputs := []*store.UserOutput{deposit(invalidID, test.amounts[0], 6), deposit(invalidID, test.amounts[1], 6), deposit(validID, "1", 9)} + unreferenced := deposit(invalidID, "0.00000004", 6) + readOutput := func(output *store.UserOutput) *store.UserOutput { + os, err := node.store.ListUserOutputsByHashAndState(ctx, userID, output.TransactionHash, 0) + require.NoError(t, err) + require.Len(t, os, 1) + return os[0] + } + // Deposits preserve their full amounts, including below-unit fractions. + for _, output := range outputs { + require.Equal(t, output.Amount, readOutput(output).Amount) + } + require.Error(t, validateSystemCallAssetAmounts(outputs)) + id := uuid.Must(uuid.NewV4()).String() + out := testBuildUserRequest(node, mix.String(), id, "", "0.0001", mtg.StorageAssetId, OperationTypeSystemCall, nil, nil, nil) + out.TestAttachActionToGroup(node.group) + req, err := node.parseRequest(out) + require.NoError(t, err) + require.NoError(t, node.store.WriteRequestIfNotExist(ctx, req)) + // The first asset is funded, but the second is not: no partial refund or + // output consumption may escape while compaction is still required. + _, err = testWriteOutputForNodes(ctx, []*mtg.SQLite3Store{md}, node.conf.AppId, invalidID, "", "", 1, decimal.RequireFromString(test.refund)) + require.NoError(t, err) + txs, compaction := node.refundSystemCallDeposits(ctx, req, outputs, mix) + require.Empty(t, txs) + require.Equal(t, validID, compaction) + for _, output := range outputs { + require.EqualValues(t, common.RequestStateInitial, readOutput(output).State) + } + ar, _, err := node.store.ReadActionResult(ctx, out.OutputId, req.Id) + require.NoError(t, err) + require.Equal(t, validID, ar.Compaction) + // Restore after compaction and refund both the invalid asset and valid SOL. + _, err = testWriteOutputForNodes(ctx, []*mtg.SQLite3Store{md}, node.conf.AppId, validID, "", "", 2, decimal.NewFromInt(1)) + require.NoError(t, err) + require.NoError(t, node.store.ResetRequest(ctx, req.Id, req.Sequence)) + out.TestAttachActionToGroup(node.group) + txs, compaction = node.refundSystemCallDeposits(ctx, req, outputs, mix) + require.Empty(t, compaction) + require.Len(t, txs, 2) + require.Equal(t, invalidID, txs[0].AssetId) + require.Equal(t, test.refund, txs[0].Amount) + require.Equal(t, validID, txs[1].AssetId) + require.Equal(t, "1", txs[1].Amount) + for _, tx := range txs { + require.Equal(t, []string{mtg.UniqueId(mix.Members()[0], mix.Members()[0])}, tx.Receivers) + require.Equal(t, int(mix.Threshold), tx.Threshold) + } + for _, output := range outputs { + saved := readOutput(output) + require.Equal(t, output.Amount, saved.Amount) + require.EqualValues(t, common.RequestStateFailed, saved.State) + } + require.EqualValues(t, common.RequestStateInitial, readOutput(unreferenced).State) + savedReq, err := node.store.ReadRequest(ctx, req.Id) + require.NoError(t, err) + require.EqualValues(t, common.RequestStateFailed, savedReq.State) + // Duplicate delivery returns cached transactions instead of refunding again. + replayed, compaction := node.processAction(ctx, out) + require.Empty(t, compaction) + require.Len(t, replayed, 2) + for i := range txs { + require.True(t, txs[i].Equal(replayed[i])) + } + }) + } +} diff --git a/solana/computer_test.go b/solana/computer_test.go index 7de6c74..6380c66 100644 --- a/solana/computer_test.go +++ b/solana/computer_test.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/binary" "encoding/hex" + "encoding/json" "fmt" "math/big" "os" @@ -22,6 +23,8 @@ import ( "github.com/MixinNetwork/safe/common" "github.com/MixinNetwork/safe/mtg" "github.com/gagliardetto/solana-go" + "github.com/gagliardetto/solana-go/programs/system" + "github.com/gagliardetto/solana-go/rpc" "github.com/gofrs/uuid/v5" "github.com/pelletier/go-toml" "github.com/shopspring/decimal" @@ -312,13 +315,17 @@ func TestFailedPostprocessCompaction(t *testing.T) { confirmId := common.UniqueId(prepare.RequestId, "confirm-fail") postId := common.UniqueId(confirmId, "post-process") nonce := node.ReadSpareNonceAccountWithCall(ctx, postId) - postTx := node.CreateRefundWithdrawalTransaction(ctx, prepare, main, nonce) + failedSignature := solana.MustSignatureFromBase58("sKxPceKjZb4PiywqwMP3Wyf9YoPqdgZZ5MLNxkpRv7qgTXVxK8UQRGkjMT47qJht5muuUPpqynkrM5C6BcYSELg") + testCacheSOLConfirmation(ctx, require, nodes, failedSignature, node.getMTGAddress(ctx), 1_000_000_000, true) + confirmedPrepare := *prepare + confirmedPrepare.Hash = sql.NullString{Valid: true, String: failedSignature.String()} + postTx := node.CreateRefundWithdrawalTransaction(ctx, &confirmedPrepare, main, nonce) require.NotNil(postTx) raw, err := postTx.MarshalBinary() require.Nil(err) - failedSignature := solana.MustSignatureFromBase58("sKxPceKjZb4PiywqwMP3Wyf9YoPqdgZZ5MLNxkpRv7qgTXVxK8UQRGkjMT47qJht5muuUPpqynkrM5C6BcYSELg") successSignature := solana.MustSignatureFromBase58("2tPHv7kbUeHRWHgVKKddQqXnjDhuX84kTyCvRy1BmCM4m4Fkq4vJmNAz8A7fXqckrSNRTAKuPmAPWnzr5T7eCChb") + testCacheSOLConfirmation(ctx, require, nodes, successSignature, node.getMTGAddress(ctx), 1_000_000_000, false) rejectedExtras := [][]byte{ // Prepare is never confirmed successfully without its Main call. encodeConfirmCallRecords([]confirmCallRecord{{ @@ -491,16 +498,20 @@ func testObserverConfirmMainCall(ctx context.Context, require *require.Assertion cid := common.UniqueId(call.RequestId, "post-process") err = node.store.OccupyNonceAccountByCall(ctx, nonce.Address, cid) require.Nil(err) - stx := node.CreatePostProcessTransaction(ctx, call, nonce, nil, nil) + signatures := []solana.Signature{ + solana.MustSignatureFromBase58("2tPHv7kbUeHRWHgVKKddQqXnjDhuX84kTyCvRy1BmCM4m4Fkq4vJmNAz8A7fXqckrSNRTAKuPmAPWnzr5T7eCChb"), + solana.MustSignatureFromBase58("42fwVqHYmfLqoqQ3XgELu72FL6t2Q2HCqY7XzkVCdVsWHGoT6DHBk7qzoUkpfjqs42ygSSnFWzarQZdpUX9tLK6r"), + } + testCacheSOLConfirmation(ctx, require, nodes, signatures[0], node.getMTGAddress(ctx), 1_000_000_000, false) + testCacheSOLConfirmation(ctx, require, nodes, signatures[1], node.getUserSolanaPublicKeyFromCall(ctx, call), 1_000_000_000, false) + confirmedMain := *call + confirmedMain.Hash = sql.NullString{Valid: true, String: signatures[1].String()} + stx := node.CreatePostProcessTransaction(ctx, &confirmedMain, nonce, nil, nil) require.NotNil(stx) raw, err := stx.MarshalBinary() require.Nil(err) id := uuid.Must(uuid.NewV4()).String() - signatures := []solana.Signature{ - solana.MustSignatureFromBase58("2tPHv7kbUeHRWHgVKKddQqXnjDhuX84kTyCvRy1BmCM4m4Fkq4vJmNAz8A7fXqckrSNRTAKuPmAPWnzr5T7eCChb"), - solana.MustSignatureFromBase58("42fwVqHYmfLqoqQ3XgELu72FL6t2Q2HCqY7XzkVCdVsWHGoT6DHBk7qzoUkpfjqs42ygSSnFWzarQZdpUX9tLK6r"), - } prepareId := common.UniqueId(call.RequestId, "prepare") extra := encodeConfirmCallRecords([]confirmCallRecord{ {Status: FlagConfirmCallSuccess, CallId: prepareId, Signature: signatures[0]}, @@ -542,6 +553,42 @@ func testObserverConfirmMainCall(ctx context.Context, require *require.Assertion return postprocess } +// The fixed confirmation signatures are test IDs (see +// getTestSystemConfirmCallMessage), not transactions for the derived test user. +// Supply matching local account metadata to every node, with no balance change +// in the main call, so its referenced assets remain available for cleanup. +func testCacheSOLConfirmation(ctx context.Context, require *require.Assertions, nodes []*Node, signature solana.Signature, source solana.PublicKey, balance uint64, failed bool) { + require.NotEmpty(getTestSystemConfirmCallMessage(signature.String())) + tx, err := solana.NewTransaction([]solana.Instruction{ + system.NewTransferInstruction(0, source, source).Build(), + }, solana.Hash{}, solana.TransactionPayer(nodes[0].SolanaPayer())) + require.NoError(err) + tx.Signatures = make([]solana.Signature, tx.Message.Header.NumRequiredSignatures) + tx.Signatures[0] = signature + accounts, err := tx.AccountMetaList() + require.NoError(err) + meta := &rpc.TransactionMeta{ + PreBalances: make([]uint64, len(accounts)), PostBalances: make([]uint64, len(accounts)), + } + for index, account := range accounts { + if account.PublicKey == source { + meta.PreBalances[index], meta.PostBalances[index] = balance, balance + } + } + if failed { + meta.Err = "test transaction failed" + } + raw, err := tx.MarshalBinary() + require.NoError(err) + result, err := json.Marshal(map[string]any{ + "meta": meta, "transaction": []string{base64.StdEncoding.EncodeToString(raw), "base64"}, + }) + require.NoError(err) + for _, node := range nodes { + require.NoError(node.store.WriteCache(ctx, "getTransaction:"+signature.String(), hex.EncodeToString(result))) + } +} + func testConfirmWithdrawal(ctx context.Context, require *require.Assertions, nodes []*Node, call *store.SystemCall) { node := nodes[0] withdrawal := &store.ConfirmedWithdrawal{ diff --git a/solana/mvm.go b/solana/mvm.go index aae88ec..63082d2 100644 --- a/solana/mvm.go +++ b/solana/mvm.go @@ -216,12 +216,12 @@ func (node *Node) processSystemCall(ctx context.Context, req *store.Request) ([] if err != nil || storage == nil { return node.failRequest(ctx, req, "") } - // External-asset deployments are MTG consensus state and can be checked - // deterministically before the call is persisted. + // Reject unsupported references before locking deposits. This includes + // deployed tokens returning as Solana assets; refund all references together. err = node.validateSystemCallReferencedAssets(ctx, os) if err != nil { logger.Printf("node.validateSystemCallReferencedAssets(%s) => %v", req.Id, err) - return node.failRequest(ctx, req, "") + return node.refundSystemCallDeposits(ctx, req, os, mix) } cid := uuid.Must(uuid.FromBytes(data[8:24])).String() @@ -279,6 +279,14 @@ func (node *Node) processSystemCall(ctx context.Context, req *store.Request) ([] return node.failRequest(ctx, req, "") } + // Validate the aggregated asset amounts before locking deposits or funding + // Prepare. Any precision loss rejects the call and refunds every reference. + err = validateSystemCallAssetAmounts(os) + if err != nil { + logger.Printf("validateSystemCallAssetAmounts(%s) => %v", call.RequestId, err) + return node.refundSystemCallDeposits(ctx, req, os, mix) + } + err = node.store.WriteInitialSystemCallWithRequest(ctx, req, call, os) logger.Printf("solana.WriteInitialSystemCallWithRequest(%v %d) => %v", call, len(os), err) if err != nil { @@ -334,11 +342,16 @@ func (node *Node) processConfirmNonce(ctx context.Context, req *store.Request) ( switch flag { case ConfirmFlagNonceAvailable: as := node.GetSystemCallRelatedAsset(ctx, os) + expectedPrepareAssets := append([]*ReferencedTxAsset(nil), as...) var sessions []*store.Session prepare, tx, err := node.getSubSystemCallFromExtra(ctx, req, extra[16:]) if err != nil { return node.failRequest(ctx, req, "") } + if len(expectedPrepareAssets) > 0 && prepare == nil { + logger.Printf("missing prepare for system call references: %s", call.RequestId) + return node.failRequest(ctx, req, "") + } if prepare != nil { prepare.Superior = call.RequestId prepare.Type = store.CallTypePrepare @@ -357,7 +370,7 @@ func (node *Node) processConfirmNonce(ctx context.Context, req *store.Request) ( if err != nil { return node.failRequest(ctx, req, "") } - err = node.comparePrepareCallWithSolanaTx(tx, as) + err = node.comparePrepareCallWithSolanaTx(tx, expectedPrepareAssets, node.getMTGAddress(ctx), solana.MustPublicKeyFromBase58(user.ChainAddress), true) logger.Printf("node.comparePrepareCallWithSolanaTx(%s) => %v", call.RequestId, err) if err != nil { return node.failRequest(ctx, req, "") @@ -991,6 +1004,17 @@ func (node *Node) failDepositRequest(ctx context.Context, out *mtg.Action, compa return nil, compaction } +// Refund references rejected before a SystemCall is persisted. These outputs +// are still Initial, unlike the Pending outputs of an already accepted call. +func (node *Node) refundSystemCallDeposits(ctx context.Context, req *store.Request, os []*store.UserOutput, mix *bot.MixAddress) ([]*mtg.Transaction, string) { + txs, compaction := node.buildRefundTxs(ctx, req, req.Id, aggregateSystemCallReferenceAssets(os), mix.Members(), int(mix.Threshold)) + err := node.store.RefundUserDepositsWithRequest(ctx, req, os, txs, compaction) + if err != nil { + panic(err) + } + return txs, compaction +} + func (node *Node) refundAndFailRequest(ctx context.Context, req *store.Request, members []string, threshod int, call *store.SystemCall, os []*store.UserOutput) ([]*mtg.Transaction, string) { as := aggregateSystemCallReferenceAssets(os) txs, compaction := node.buildRefundTxs(ctx, req, call.RequestId, as, members, threshod) @@ -1024,6 +1048,9 @@ func (node *Node) failSystemCall(ctx context.Context, req *store.Request, call * if err != nil || referenceCall == nil { panic(fmt.Errorf("store.ReadSystemCallByRequestId(%s) => %v %v", call.RequestId, referenceCall, err)) } + // Preserve the persisted state for reference lookup, but use the confirmed + // attempt's signature for deterministic cleanup balance checks. + referenceCall.Hash = call.Hash var outputs []*store.UserOutput var mix *bot.MixAddress diff --git a/solana/observer.go b/solana/observer.go index 38fc7bc..e911e4e 100644 --- a/solana/observer.go +++ b/solana/observer.go @@ -2,6 +2,7 @@ package solana import ( "context" + "database/sql" "encoding/base64" "encoding/binary" "errors" @@ -884,7 +885,7 @@ func (node *Node) handleSignedCall(ctx context.Context, call *store.SystemCall) if err != nil { panic(err) } - if index >= 0 { + if tx.IsSigner(publicKey) && index >= 0 { sig, err := base64.StdEncoding.DecodeString(call.Signature.String) if err != nil { panic(err) @@ -946,6 +947,10 @@ func (node *Node) processSuccessedCall(ctx context.Context, call *store.SystemCa func (node *Node) processFailedCall(ctx context.Context, call *store.SystemCall, signature solana.Signature, successful []confirmCallRecord, callError error) error { logger.Printf("node.processFailedCall(%s)", call.RequestId) + // Builders use the same confirmed balance snapshot as confirmation replay. + failed := *call + failed.Hash = sql.NullString{Valid: true, String: signature.String()} + call = &failed id := common.UniqueId(call.RequestId, "confirm-fail") cid := common.UniqueId(id, "post-process") nonce := node.ReadSpareNonceAccountWithCall(ctx, cid) diff --git a/solana/post_process_amount_test.go b/solana/post_process_amount_test.go new file mode 100644 index 0000000..bb6ff71 --- /dev/null +++ b/solana/post_process_amount_test.go @@ -0,0 +1,242 @@ +package solana + +import ( + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "math/big" + "path/filepath" + "testing" + + solanaApp "github.com/MixinNetwork/computer/apps/solana" + "github.com/MixinNetwork/computer/store" + "github.com/gagliardetto/solana-go" + "github.com/gagliardetto/solana-go/programs/system" + "github.com/gagliardetto/solana-go/programs/token" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/require" +) + +func TestPostProcessActualAmountsMatchSkippedExpectations(t *testing.T) { + ctx := context.Background() + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "amounts.sqlite")) + require.NoError(t, err) + defer st.Close() + payer := solana.NewWallet() + user := solana.NewWallet().PublicKey() + entry := solana.NewWallet().PublicKey() + mint := solana.NewWallet().PublicKey() + nonce := solana.NewWallet().PublicKey() + node := &Node{store: st, conf: &Configuration{SolanaKey: payer.PrivateKey.String()}} + // Cache a non-NFT result; these tests need no live account state. + require.NoError(t, st.WriteCache(ctx, "getAccount:"+mint.String(), hex.EncodeToString([]byte(`{"value":{"data":["","base64"]}}`)))) + for _, program := range []solana.PublicKey{solana.TokenProgramID, solana.Token2022ProgramID} { + for _, kind := range []solanaApp.InitialAssetMovementKind{solanaApp.InitialAssetMovementTransfer, solanaApp.InitialAssetMovementBurn} { + for _, test := range []struct { + name string + expected string + actual uint64 + decimals uint8 + wantErr bool + }{ + {name: "zero expected", expected: "0", actual: 1_000_000, decimals: 6, wantErr: true}, + {name: "negative expected", expected: "-1", actual: 1_000_000, decimals: 6, wantErr: true}, + {name: "positive expected below dust", expected: "0.000000001", actual: 1_000_000_000, decimals: 9, wantErr: true}, + {name: "correct positive amount", expected: "1", actual: 1_000_000, decimals: 6}, + {name: "excessive positive amount", expected: "1", actual: 2_000_000, decimals: 6, wantErr: true}, + {name: "actual dust remains exempt", expected: "0", actual: 1, decimals: 9}, + } { + t.Run(program.String()+"/"+string(kind)+"/"+test.name, func(t *testing.T) { + userATA := solanaApp.FindAssociatedTokenAddress(user, mint, program) + entryATA := solanaApp.FindAssociatedTokenAddress(entry, mint, program) + var ix solana.Instruction + if kind == solanaApp.InitialAssetMovementTransfer { + ix = token.NewTransferCheckedInstruction(test.actual, test.decimals, userATA, mint, entryATA, user, nil).Build() + } else { + ix = token.NewBurnCheckedInstruction(test.actual, test.decimals, userATA, mint, user, nil).Build() + } + data, err := ix.Data() + require.NoError(t, err) + tx, err := solana.NewTransaction([]solana.Instruction{ + system.NewAdvanceNonceAccountInstruction(nonce, solana.SysVarRecentBlockHashesPubkey, payer.PublicKey()).Build(), + solana.NewInstruction(program, ix.Accounts(), data), + }, solana.Hash{}, solana.TransactionPayer(payer.PublicKey())) + require.NoError(t, err) + require.NoError(t, node.VerifySubSystemCallEnvelope(tx, user, true)) + require.NoError(t, node.verifySubSystemCall(ctx, tx, entry, user, false)) + transfers, burns, err := buildInitialAssetMovementMaps(tx, "", payer.PublicKey().String()) + require.NoError(t, err) + actual := transfers + if kind == solanaApp.InitialAssetMovementBurn { + actual = burns + } + expected := map[string]*ReferencedTxAsset{ + mint.String(): {Address: mint.String(), Decimal: int(test.decimals), Amount: decimal.RequireFromString(test.expected)}, + } + err = node.comparePostProcessMovements(ctx, kind, expected, actual, nil) + if test.wantErr { + require.ErrorContains(t, err, "invalid "+string(kind)+" user balance change") + } else { + require.NoError(t, err) + } + }) + } + } + } +} + +func TestPostProcessAmountExemptions(t *testing.T) { + ctx := context.Background() + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "exemptions.sqlite")) + require.NoError(t, err) + defer st.Close() + node := &Node{store: st} + mint := solana.NewWallet().PublicKey().String() + nft := solana.NewWallet().PublicKey().String() + require.NoError(t, st.WriteCache(ctx, "getAccount:"+mint, hex.EncodeToString([]byte(`{"value":{"data":["","base64"]}}`)))) + // Standard SPL mint: supply 1, decimals 0, initialized. + nftData := make([]byte, 82) + nftData[36], nftData[45] = 1, 1 + nftAccount, err := json.Marshal(map[string]any{"value": map[string]any{ + "data": []string{base64.StdEncoding.EncodeToString(nftData), "base64"}, + }}) + require.NoError(t, err) + require.NoError(t, st.WriteCache(ctx, "getAccount:"+nft, hex.EncodeToString(nftAccount))) + for _, kind := range []solanaApp.InitialAssetMovementKind{solanaApp.InitialAssetMovementTransfer, solanaApp.InitialAssetMovementBurn} { + t.Run(string(kind), func(t *testing.T) { + for _, amount := range []string{"0", "-1", "0.000000001"} { + expected := map[string]*ReferencedTxAsset{ + mint: {Decimal: 9, Amount: decimal.RequireFromString(amount)}, + } + require.NoError(t, node.comparePostProcessMovements(ctx, kind, expected, nil, nil)) + } + actual := map[string]*solanaApp.InitialAssetMovement{ + mint: {Kind: kind, TokenAddress: mint, Decimal: 6, Value: big.NewInt(1_000_000)}, + } + require.ErrorContains(t, node.comparePostProcessMovements(ctx, kind, nil, actual, nil), "unexpected "+string(kind)) + expectedNFT := map[string]*ReferencedTxAsset{nft: {Amount: decimal.Zero}} + actualNFT := map[string]*solanaApp.InitialAssetMovement{ + nft: {Kind: kind, TokenAddress: nft, Decimal: 0, Value: big.NewInt(1)}, + } + require.NoError(t, node.comparePostProcessMovements(ctx, kind, expectedNFT, actualNFT, nil)) + }) + } +} + +func TestPostProcessMovementDecimals(t *testing.T) { + ctx := context.Background() + st, err := store.OpenSQLite3Store(filepath.Join(t.TempDir(), "decimals.sqlite")) + require.NoError(t, err) + defer st.Close() + node := &Node{store: st} + mint := solana.NewWallet().PublicKey().String() + require.NoError(t, st.WriteCache(ctx, "getAccount:"+mint, hex.EncodeToString([]byte(`{"value":{"data":["","base64"]}}`)))) + for _, kind := range []solanaApp.InitialAssetMovementKind{solanaApp.InitialAssetMovementTransfer, solanaApp.InitialAssetMovementBurn} { + for _, test := range []struct { + name string + expected string + decimals uint8 + value int64 + wantErr bool + }{ + {name: "wrong decimals same raw amount", expected: "1", decimals: 9, value: 1_000_000, wantErr: true}, + {name: "wrong decimals looks like dust", expected: "0", decimals: 18, value: 1_000_000, wantErr: true}, + {name: "wrong decimals zero amount", expected: "0", decimals: 9, value: 0, wantErr: true}, + {name: "correct decimals", expected: "1", decimals: 6, value: 1_000_000}, + {name: "correct zero amount", expected: "0", decimals: 6, value: 0}, + } { + t.Run(string(kind)+"/"+test.name, func(t *testing.T) { + expected := map[string]*ReferencedTxAsset{mint: {Decimal: 6, Amount: decimal.RequireFromString(test.expected)}} + actual := map[string]*solanaApp.InitialAssetMovement{ + mint: {Kind: kind, TokenAddress: mint, Decimal: test.decimals, Value: big.NewInt(test.value)}, + } + err := node.comparePostProcessMovements(ctx, kind, expected, actual, nil) + if test.wantErr { + require.ErrorContains(t, err, "decimals") + } else { + require.NoError(t, err) + } + }) + } + } +} + +func TestInitialMovementDecimalsBeforeAggregation(t *testing.T) { + payer := solana.NewWallet().PublicKey() + user := solana.NewWallet().PublicKey() + entry := solana.NewWallet().PublicKey() + mint := solana.NewWallet().PublicKey() + type instruction struct { + burn bool + decimals uint8 + amount uint64 + fromPayer bool + } + for _, program := range []solana.PublicKey{solana.TokenProgramID, solana.Token2022ProgramID} { + for _, test := range []struct { + name string + instructions []instruction + includeUser bool + excludePayer bool + wantErr bool + wantAmount int64 + }{ + {name: "consistent transfers", instructions: []instruction{{decimals: 6, amount: 1_000_000}, {decimals: 6, amount: 1_000_000}}, wantAmount: 2_000_000}, + {name: "consistent burns", instructions: []instruction{{burn: true, decimals: 6, amount: 1_000_000}, {burn: true, decimals: 6, amount: 1_000_000}}, wantAmount: 2_000_000}, + {name: "mixed transfer decimals", instructions: []instruction{{decimals: 6, amount: 500_000}, {decimals: 9, amount: 500_000}}, wantErr: true}, + {name: "mixed burn decimals", instructions: []instruction{{burn: true, decimals: 6, amount: 500_000}, {burn: true, decimals: 9, amount: 500_000}}, wantErr: true}, + {name: "wrong first instruction", instructions: []instruction{{decimals: 9, amount: 500_000}, {decimals: 6, amount: 500_000}}, wantErr: true}, + {name: "wrong zero amount instruction", instructions: []instruction{{decimals: 6, amount: 1_000_000}, {decimals: 9, amount: 0}}, wantErr: true}, + {name: "mixed transfer and burn decimals", instructions: []instruction{{decimals: 6, amount: 500_000}, {burn: true, decimals: 9, amount: 500_000}}, wantErr: true}, + {name: "exclude payer before aggregation", instructions: []instruction{{decimals: 9, amount: 1_000_000, fromPayer: true}, {decimals: 6, amount: 1_000_000}}, excludePayer: true, wantAmount: 1_000_000}, + {name: "include user before aggregation", instructions: []instruction{{decimals: 9, amount: 1_000_000, fromPayer: true}, {decimals: 6, amount: 1_000_000}}, includeUser: true, wantAmount: 1_000_000}, + } { + t.Run(program.String()+"/"+test.name, func(t *testing.T) { + var instructions []solana.Instruction + for _, spec := range test.instructions { + sender := user + if spec.fromPayer { + sender = payer + } + source := solanaApp.FindAssociatedTokenAddress(sender, mint, program) + destination := solanaApp.FindAssociatedTokenAddress(entry, mint, program) + var ix solana.Instruction + if spec.burn { + ix = token.NewBurnCheckedInstruction(spec.amount, spec.decimals, source, mint, sender, nil).Build() + } else { + ix = token.NewTransferCheckedInstruction(spec.amount, spec.decimals, source, mint, destination, sender, nil).Build() + } + data, err := ix.Data() + require.NoError(t, err) + instructions = append(instructions, solana.NewInstruction(program, ix.Accounts(), data)) + } + tx, err := solana.NewTransaction(instructions, solana.Hash{}, solana.TransactionPayer(payer)) + require.NoError(t, err) + var include, exclude string + if test.includeUser { + include = user.String() + } + if test.excludePayer { + exclude = payer.String() + } + transfers, burns, err := buildInitialAssetMovementMaps(tx, include, exclude) + if test.wantErr { + require.ErrorContains(t, err, "inconsistent movement decimals") + require.Nil(t, transfers) + require.Nil(t, burns) + return + } + require.NoError(t, err) + total := new(big.Int) + for _, ledger := range []map[string]*solanaApp.InitialAssetMovement{transfers, burns} { + if movement := ledger[mint.String()]; movement != nil { + require.EqualValues(t, 6, movement.Decimal) + total.Add(total, movement.Value) + } + } + require.Equal(t, test.wantAmount, total.Int64()) + }) + } + } +} diff --git a/solana/solana.go b/solana/solana.go index accef34..628100d 100644 --- a/solana/solana.go +++ b/solana/solana.go @@ -33,18 +33,64 @@ const ( SolanaTxRetry = 10 SolanaMinimumHeight = 442271000 - // SOL cleanup uses the historical 165-byte rent minimum as a fixed protocol - // dust threshold, not as a quote for current Solana rent. Observers and - // validators must make the same selection during replay and rent changes. - // Changing this value requires a coordinated protocol upgrade. - solanaCleanupDustLamports uint64 = 2_039_280 + // Fixed cleanup policy shared by observers and validators during replay. + // Dust is the Mixin processing minimum; rent protects the source balance. + solanaCleanupDustLamports uint64 = 100_000 + solanaCleanupRentLamports uint64 = 650_240 ) var errInvalidAddressLookup = errors.New("invalid address lookup") func isSOLCleanupDust(assetID string, lamports decimal.Decimal) bool { return assetID == solanaApp.SolanaChainBase && - lamports.Cmp(decimal.NewFromUint64(solanaCleanupDustLamports)) <= 0 + lamports.Cmp(decimal.NewFromUint64(solanaCleanupDustLamports)) < 0 +} + +func isSOLCleanupRentUnsafe(balance, amount uint64) (bool, error) { + if amount > balance { + return false, fmt.Errorf("SOL cleanup exceeds balance: %d %d", amount, balance) + } + remaining := balance - amount + return remaining != 0 && remaining < solanaCleanupRentLamports, nil +} + +// Use confirmed transaction metadata so replay never depends on a live balance. +// A nil balance means the source account is absent from the transaction. +func (node *Node) cleanupSOLBalance(ctx context.Context, call *store.SystemCall, tx *solana.Transaction, meta *rpc.TransactionMeta, source solana.PublicKey) (*uint64, error) { + if tx == nil || meta == nil { + if call == nil || !call.Hash.Valid || call.Hash.String == "" { + return nil, fmt.Errorf("missing confirmed cleanup transaction") + } + result, err := node.RPCGetTransaction(ctx, call.Hash.String) + if err != nil { + return nil, err + } + if result == nil || result.Meta == nil { + return nil, fmt.Errorf("missing cleanup transaction metadata: %s", call.Hash.String) + } + tx, err = result.Transaction.GetTransaction() + if err != nil { + return nil, err + } + meta = result.Meta + } + if err := node.processTransactionWithAddressLookups(ctx, tx); err != nil { + return nil, err + } + accounts, err := tx.AccountMetaList() + if err != nil { + return nil, err + } + for index, account := range accounts { + if account.PublicKey != source { + continue + } + if index >= len(meta.PostBalances) { + return nil, fmt.Errorf("missing cleanup source balance: %s", source) + } + return &meta.PostBalances[index], nil + } + return nil, nil } func (node *Node) addressLookupTableLoop(ctx context.Context) { @@ -563,31 +609,7 @@ func (node *Node) createPostProcessTransaction(ctx context.Context, call *store. } } - var transfers []*solanaApp.TokenTransfer - for _, asset := range assets { - dust := decimal.RequireFromString("0.00000001") - if asset.Amount.Cmp(dust) < 0 { - logger.Printf("skip referenced asset in post-process: %v", asset) - continue - } - amount := asset.Amount.Mul(decimal.New(1, int32(asset.Decimal))) - if !amount.BigInt().IsUint64() { - continue - } - if isSOLCleanupDust(asset.AssetId, amount) { - logger.Printf("skip SOL transfer in post-process: %v", asset) - continue - } - transfers = append(transfers, &solanaApp.TokenTransfer{ - SolanaAsset: asset.Solana, - AssetId: asset.AssetId, - ChainId: asset.ChainId, - Mint: solana.MustPublicKeyFromBase58(asset.Address), - Destination: solana.MustPublicKeyFromBase58(node.conf.SolanaDepositEntry), - Amount: amount.BigInt().Uint64(), - Decimals: uint8(asset.Decimal), - }) - } + transfers := node.buildPostProcessTransfers(ctx, call, source, meta, user, assets) if len(transfers) == 0 { return nil } @@ -623,6 +645,55 @@ func (node *Node) createPostProcessTransaction(ctx context.Context, call *store. return tx } +// Select cleanup movements before constructing a transaction. Missing Main +// source accounts suppress native SOL only; token cleanup is independent. +func (node *Node) buildPostProcessTransfers(ctx context.Context, call *store.SystemCall, tx *solana.Transaction, meta *rpc.TransactionMeta, user solana.PublicKey, assets map[string]*ReferencedTxAsset) []*solanaApp.TokenTransfer { + var transfers []*solanaApp.TokenTransfer + for _, asset := range assets { + dust := decimal.RequireFromString("0.00000001") + if asset.Amount.Cmp(dust) < 0 { + logger.Printf("skip referenced asset in post-process: %v", asset) + continue + } + amount := asset.Amount.Mul(decimal.New(1, int32(asset.Decimal))) + if !amount.BigInt().IsUint64() { + continue + } + if isSOLCleanupDust(asset.AssetId, amount) { + logger.Printf("skip SOL transfer in post-process: %v", asset) + continue + } + if asset.AssetId == solanaApp.SolanaChainBase { + balance, err := node.cleanupSOLBalance(ctx, call, tx, meta, user) + if err != nil { + panic(err) + } + if balance == nil { + logger.Printf("skip SOL cleanup absent from Main: %s", call.RequestId) + continue + } + unsafe, err := isSOLCleanupRentUnsafe(*balance, amount.BigInt().Uint64()) + if err != nil { + panic(err) + } + if unsafe { + logger.Printf("skip SOL cleanup leaving insufficient rent: %s", call.RequestId) + continue + } + } + transfers = append(transfers, &solanaApp.TokenTransfer{ + SolanaAsset: asset.Solana, + AssetId: asset.AssetId, + ChainId: asset.ChainId, + Mint: solana.MustPublicKeyFromBase58(asset.Address), + Destination: solana.MustPublicKeyFromBase58(node.conf.SolanaDepositEntry), + Amount: amount.BigInt().Uint64(), + Decimals: uint8(asset.Decimal), + }) + } + return transfers +} + func (node *Node) CreateRefundWithdrawalTransaction(ctx context.Context, prepare, call *store.SystemCall, nonce *store.NonceAccount) *solana.Transaction { return node.createRefundWithdrawalTransaction(ctx, prepare, call, nonce, nil) } @@ -715,6 +786,23 @@ func (node *Node) buildRefundWithdrawalTransfers(ctx context.Context, prepare, c logger.Printf("skip SOL transfer in refund-withdrawal: %v", asset) continue } + if asset.AssetId == solanaApp.SolanaChainBase { + balance, err := node.cleanupSOLBalance(ctx, prepare, nil, nil, node.getMTGAddress(ctx)) + if err != nil { + panic(err) + } + if balance == nil { + panic(fmt.Errorf("missing refund source balance: %s", prepare.RequestId)) + } + unsafe, err := isSOLCleanupRentUnsafe(*balance, amount.BigInt().Uint64()) + if err != nil { + panic(err) + } + if unsafe { + logger.Printf("skip SOL refund leaving insufficient rent: %s", prepare.RequestId) + continue + } + } transfers = append(transfers, &solanaApp.TokenTransfer{ SolanaAsset: asset.Solana, AssetId: asset.AssetId, @@ -931,6 +1019,10 @@ func buildBalanceMap(balances []rpc.TokenBalance, owner *solana.PublicKey) map[s } func (node *Node) VerifySubSystemCall(ctx context.Context, tx *solana.Transaction, groupDepositEntry, user solana.PublicKey) error { + return node.verifySubSystemCall(ctx, tx, groupDepositEntry, user, true) +} + +func (node *Node) verifySubSystemCall(ctx context.Context, tx *solana.Transaction, groupDepositEntry, user solana.PublicKey, allowMint bool) error { for index, ix := range tx.Message.Instructions { accounts, err := ix.ResolveInstructionAccounts(&tx.Message) if err != nil { @@ -964,6 +1056,9 @@ func (node *Node) VerifySubSystemCall(ctx context.Context, tx *solana.Transactio return fmt.Errorf("invalid system program instruction: %d", index) case solana.TokenProgramID, solana.Token2022ProgramID: if mint, ok := solanaApp.DecodeTokenMintTo(accounts, ix.Data); ok { + if !allowMint { + return fmt.Errorf("mint to is not allowed in post-process call") + } to := mint.GetDestinationAccount().PublicKey token := mint.GetMintAccount().PublicKey ata := solanaApp.FindAssociatedTokenAddress(user, token, programKey) diff --git a/solana/system_call.go b/solana/system_call.go index e8d0933..9015c3d 100644 --- a/solana/system_call.go +++ b/solana/system_call.go @@ -16,9 +16,12 @@ import ( mc "github.com/MixinNetwork/mixin/common" "github.com/MixinNetwork/mixin/crypto" "github.com/MixinNetwork/mixin/logger" + "github.com/MixinNetwork/safe/apps/ethereum" "github.com/MixinNetwork/safe/common" "github.com/gagliardetto/solana-go" + tokenAta "github.com/gagliardetto/solana-go/programs/associated-token-account" computebudget "github.com/gagliardetto/solana-go/programs/compute-budget" + "github.com/gagliardetto/solana-go/programs/system" "github.com/gofrs/uuid/v5" "github.com/shopspring/decimal" ) @@ -221,10 +224,23 @@ func (node *Node) validateSystemCallParameters(ctx context.Context, req *store.R func (node *Node) validateSystemCallReferencedAssets(ctx context.Context, os []*store.UserOutput) error { checked := make(map[string]bool) for _, output := range os { - if output.ChainId == solanaApp.SolanaChainBase || checked[output.AssetId] { + if checked[output.AssetId] { continue } checked[output.AssetId] = true + if output.ChainId == solanaApp.SolanaChainBase { + // Original BTC and its Solana representation have different Mixin + // asset IDs. Reject a returning deployed token by its mint address. + deployed, err := node.store.ReadDeployedAssetByAddress(ctx, output.Asset.AssetKey) + if err != nil { + panic(fmt.Errorf("store.ReadDeployedAssetByAddress(%s) => %v", output.Asset.AssetKey, err)) + } + if deployed != nil { + return fmt.Errorf("deployed Solana mint is not allowed in system call deposits: %s %s", output.AssetId, deployed.Address) + } + continue + } + // Original external assets are supported once their mint is deployed. deployed, err := node.store.ReadDeployedAsset(ctx, output.AssetId) if err != nil { panic(fmt.Errorf("store.ReadDeployedAsset(%s) => %v", output.AssetId, err)) @@ -236,6 +252,18 @@ func (node *Node) validateSystemCallReferencedAssets(ctx context.Context, os []* return nil } +func validateSystemCallAssetAmounts(os []*store.UserOutput) error { + // Match Prepare's aggregation: individually small deposits may add up to a + // representable amount. External assets already use the deployed precision. + for _, asset := range aggregateSystemCallReferenceAssets(os) { + truncated := asset.Amount.Truncate(int32(asset.Decimal)) + if truncated.IsZero() || !truncated.Equal(asset.Amount) { + return fmt.Errorf("unrepresentable system call asset amount: %s %s decimals=%d", asset.AssetId, asset.Amount, asset.Decimal) + } + } + return nil +} + func (node *Node) readSystemCallFeeInfo(ctx context.Context, req *store.Request) (*store.FeeInfo, error) { extra := req.ExtraBytes() switch len(extra) { @@ -348,8 +376,9 @@ func (node *Node) getPostProcessCall(ctx context.Context, req *store.Request, fl if err != nil { return nil, err } - err = node.VerifySubSystemCall(ctx, tx, mtgDeposit, solana.MustPublicKeyFromBase58(user.ChainAddress)) - logger.Printf("node.VerifySubSystemCall(%s) => %v", user.ChainAddress, err) + // Cleanup must never mint, even when the mint destination is the user's ATA. + err = node.verifySubSystemCall(ctx, tx, mtgDeposit, solana.MustPublicKeyFromBase58(user.ChainAddress), false) + logger.Printf("node.verifySubSystemCall(%s) => %v", user.ChainAddress, err) if err != nil { return nil, err } @@ -559,7 +588,11 @@ func (node *Node) checkUserSystemCall(ctx context.Context, tx *solana.Transactio return nil } - // ensure the transaction is signed by fee payer + // Require the node to pay Main's fees. Being a signer alone would allow + // fees to reduce the user's funded balance even when Main fails. + if len(tx.Message.AccountKeys) == 0 || tx.Message.AccountKeys[0] != node.SolanaPayer() { + return fmt.Errorf("invalid system call fee payer") + } if !tx.IsSigner(node.SolanaPayer()) { return fmt.Errorf("tx.IsSigner(payer) => %t", false) } @@ -577,43 +610,152 @@ func (node *Node) checkUserSystemCall(ctx context.Context, tx *solana.Transactio return nil } -func (node *Node) comparePrepareCallWithSolanaTx(tx *solana.Transaction, as []*ReferencedTxAsset) error { - changes := make(map[string]*solanaApp.Transfer) - for _, ix := range tx.Message.Instructions { - transfer := solanaApp.ExtractInitialTransfersFromInstruction(&tx.Message, ix) - if transfer == nil || transfer.Sender == node.SolanaPayer().String() { - continue +type prepareMovement struct { + Kind string + TokenAddress string + Source string + Destination string +} + +func (m prepareMovement) key() string { + return strings.Join([]string{m.Kind, m.TokenAddress, m.Source, m.Destination}, ":") +} + +func (node *Node) comparePrepareCallWithSolanaTx(tx *solana.Transaction, as []*ReferencedTxAsset, mtg, user solana.PublicKey, allowUnknownPayerFee bool) error { + expected := make(map[string]*big.Int) + for _, a := range as { + amount := a.Amount.Mul(decimal.New(1, int32(a.Decimal))).BigInt() + if amount.Sign() <= 0 { + return fmt.Errorf("invalid prepare asset amount: %s %s", a.AssetId, a.Amount.String()) } - key := transfer.TokenAddress - old := changes[key] - if old != nil { - changes[key].Value = new(big.Int).Add(old.Value, transfer.Value) - continue + + var movement prepareMovement + switch { + case a.Solana && a.AssetId == a.ChainId: + source := mtg.String() + if a.Fee { + source = node.SolanaPayer().String() + } + movement = prepareMovement{ + Kind: "system-transfer", + TokenAddress: a.Address, + Source: source, + Destination: user.String(), + } + case a.Solana: + movement = prepareMovement{ + Kind: "token-transfer", + TokenAddress: a.Address, + Source: mtg.String(), + Destination: user.String(), + } + default: + movement = prepareMovement{ + Kind: "token-mint", + TokenAddress: a.Address, + Destination: user.String(), + } } - changes[key] = transfer + + addPrepareMovement(expected, movement, amount) } - assets := make(map[string]*ReferencedTxAsset, len(as)) - for _, a := range as { - if assets[a.Address] != nil { - assets[a.Address].Amount = assets[a.Address].Amount.Add(a.Amount) + actual := make(map[string]*big.Int) + for index, ix := range tx.Message.Instructions { + programKey, err := tx.Message.Program(ix.ProgramIDIndex) + if err != nil { + panic(err) + } + accounts, err := ix.ResolveInstructionAccounts(&tx.Message) + if err != nil { + panic(err) + } + + switch programKey { + case system.ProgramID: + transfer, ok := solanaApp.DecodeSystemTransfer(accounts, ix.Data) + if !ok { + continue + } + recipient := transfer.GetRecipientAccount().PublicKey + if !recipient.Equals(user) { + return fmt.Errorf("invalid prepare SOL recipient: %s", recipient.String()) + } + movement := prepareMovement{ + Kind: "system-transfer", + TokenAddress: solanaApp.SolanaEmptyAddress, + Source: transfer.GetFundingAccount().PublicKey.String(), + Destination: user.String(), + } + if allowUnknownPayerFee && movement.Source == node.SolanaPayer().String() { + continue + } + addPrepareMovement(actual, movement, new(big.Int).SetUint64(*transfer.Lamports)) + case solana.TokenProgramID, solana.Token2022ProgramID: + if transfer, ok := solanaApp.DecodeTokenTransferChecked(accounts, ix.Data); ok { + mint := transfer.GetMintAccount().PublicKey + recipient := transfer.GetDestinationAccount().PublicKey + userAta := solanaApp.FindAssociatedTokenAddress(user, mint, programKey) + if !recipient.Equals(userAta) { + return fmt.Errorf("invalid prepare token recipient: %s", recipient.String()) + } + movement := prepareMovement{ + Kind: "token-transfer", + TokenAddress: mint.String(), + Source: transfer.GetOwnerAccount().PublicKey.String(), + Destination: user.String(), + } + addPrepareMovement(actual, movement, new(big.Int).SetUint64(*transfer.Amount)) + continue + } + if mint, ok := solanaApp.DecodeTokenMintTo(accounts, ix.Data); ok { + token := mint.GetMintAccount().PublicKey + recipient := mint.GetDestinationAccount().PublicKey + userAta := solanaApp.FindAssociatedTokenAddress(user, token, programKey) + if !recipient.Equals(userAta) { + return fmt.Errorf("invalid prepare mint recipient: %s", recipient.String()) + } + movement := prepareMovement{ + Kind: "token-mint", + TokenAddress: token.String(), + Destination: user.String(), + } + addPrepareMovement(actual, movement, new(big.Int).SetUint64(*mint.Amount)) + continue + } + case tokenAta.ProgramID, solana.ComputeBudget, solana.MemoProgramID: continue + default: + return fmt.Errorf("invalid prepare instruction %d program: %s", index, programKey.String()) } - assets[a.Address] = a } - for addr, change := range changes { - a := assets[addr] - if a == nil { - return fmt.Errorf("invalid missed referenced asset: %v", a) + + for key, amount := range actual { + want := expected[key] + if want == nil { + return fmt.Errorf("unexpected prepare asset movement: %s %s", key, amount.String()) } - expected := a.Amount.Mul(decimal.New(1, int32(a.Decimal))).BigInt() - if expected.Cmp(change.Value) != 0 { - return fmt.Errorf("invalid referenced asset: %s %s %s", a.AssetId, change.Value.String(), expected.String()) + if want.Cmp(amount) != 0 { + return fmt.Errorf("invalid prepare asset amount: %s %s %s", key, amount.String(), want.String()) + } + } + for key, want := range expected { + got := actual[key] + if got == nil { + return fmt.Errorf("missing prepare asset movement: %s %s", key, want.String()) } } return nil } +func addPrepareMovement(m map[string]*big.Int, movement prepareMovement, amount *big.Int) { + key := movement.key() + if m[key] == nil { + m[key] = new(big.Int) + } + m[key].Add(m[key], amount) +} + func (node *Node) comparePostCallWithSolanaTx(ctx context.Context, as []*ReferencedTxAsset, tx *solana.Transaction, signature, user string) error { rpcTx, err := node.RPCGetTransaction(ctx, signature) if err != nil || rpcTx == nil { @@ -631,67 +773,102 @@ func (node *Node) comparePostCallWithSolanaTx(ctx context.Context, as []*Referen panic(err) } - assets := make(map[string]*ReferencedTxAsset) + expectedTransfers := make(map[string]*ReferencedTxAsset) + expectedBurns := make(map[string]*ReferencedTxAsset) for _, a := range as { - if assets[a.Address] != nil { - assets[a.Address].Amount = assets[a.Address].Amount.Add(a.Amount) - continue + // Keep Solana transfers and external-asset burns in separate ledgers. + // A mixed burn+transfer for the same mint must not satisfy one expected amount. + if a.Solana { + addExpectedSystemCallMovement(expectedTransfers, a) + } else { + addExpectedSystemCallMovement(expectedBurns, a) } - assets[a.Address] = a } cs := node.buildUserBalanceChangesFromMeta(ctx, utx, rpcTx.Meta, solana.MPK(user)) for address, change := range cs { - old := assets[address] - if old != nil { - assets[address].Amount = assets[address].Amount.Add(change.Amount) + if old := expectedTransfers[address]; old != nil { + old.Amount = old.Amount.Add(change.Amount) + continue + } + if old := expectedBurns[address]; old != nil { + old.Amount = old.Amount.Add(change.Amount) continue } if !change.Amount.IsPositive() { continue } - assets[address] = &ReferencedTxAsset{ + asset := &ReferencedTxAsset{ + Solana: true, Address: address, Decimal: int(change.Decimals), Amount: change.Amount, + AssetId: solanaApp.SolanaChainBase, + ChainId: solanaApp.SolanaChainBase, } - } + if address != solanaApp.SolanaEmptyAddress { + asset.AssetId = ethereum.BuildChainAssetId(solanaApp.SolanaChainBase, address) - changes := make(map[string]*solanaApp.Transfer) - for _, ix := range tx.Message.Instructions { - transfer := solanaApp.ExtractInitialTransfersFromInstruction(&tx.Message, ix) - if transfer == nil || transfer.Sender == node.SolanaPayer().String() { - continue + da, err := node.store.ReadDeployedAssetByAddress(ctx, address) + if err != nil { + panic(fmt.Errorf("store.ReadDeployedAssetByAddress(%s) => %v", address, err)) + } + if da != nil { + asset.Solana = false + asset.AssetId = da.AssetId + asset.ChainId = da.ChainId + } } - key := transfer.TokenAddress - old := changes[key] - if old != nil { - changes[key].Value = new(big.Int).Add(old.Value, transfer.Value) - continue + if asset.Solana { + addExpectedSystemCallMovement(expectedTransfers, asset) + } else { + addExpectedSystemCallMovement(expectedBurns, asset) } - changes[key] = transfer } - for address, c := range changes { - amount := decimal.NewFromBigInt(c.Value, -int32(c.Decimal)) - dust := decimal.RequireFromString("0.00000001") - if amount.Cmp(dust) < 0 { - continue - } - isNFT, err := node.RPCCheckNFT(ctx, address) + actualTransfers, actualBurns, err := buildInitialAssetMovementMaps(tx, "", node.SolanaPayer().String()) + if err != nil { + return err + } + var solBalance *uint64 + expectedSOL := expectedTransfers[solanaApp.SolanaEmptyAddress] + // Any actual SOL transfer needs a balance/rent check, even below dust. + // When SOL is omitted, only a positive non-dust expectation needs a balance + // to decide whether omission is allowed. Dust-only expectations need no + // snapshot, so they cannot block an otherwise valid token cleanup. + needsSOLBalance := actualTransfers[solanaApp.SolanaEmptyAddress] != nil + if expectedSOL != nil && expectedSOL.Amount.IsPositive() { + needsSOLBalance = needsSOLBalance || !isSOLCleanupDust(expectedSOL.AssetId, expectedSOL.Amount.Shift(int32(expectedSOL.Decimal))) + } + if needsSOLBalance { + // Read Main's confirmed snapshot, not the cleanup transaction or a live + // account balance, so observers and validators agree during replay. + solBalance, err = node.cleanupSOLBalance(ctx, nil, utx, rpcTx.Meta, solana.MPK(user)) if err != nil { - panic(fmt.Errorf("node.RPCCheckNFT(%s) => %v", address, err)) - } else if isNFT { - continue - } - - old := assets[address] - if old == nil { - return fmt.Errorf("invalid missed user balance change: %s", address) + // RPC/metadata errors must not be treated as permission to omit SOL. + return err } - if old.Amount.Cmp(amount) != 0 { - return fmt.Errorf("invalid user balance change: %s %s %s", address, amount.String(), old.Amount.String()) + if solBalance == nil { + // nil means Main omitted the user's account; a real zero balance is + // a non-nil pointer. The builder skips SOL in this case, so reject + // proposals that nevertheless include a SOL transfer. + if actualTransfers[solanaApp.SolanaEmptyAddress] != nil { + return fmt.Errorf("SOL cleanup source absent from Main") + } + // Match the builder by dropping only the in-memory SOL expectation. + // Token transfer and burn expectations still require comparison below. + delete(expectedTransfers, solanaApp.SolanaEmptyAddress) } } + // Compare each instruction class independently so one class cannot make up + // for a shortfall in the other. + err = node.comparePostProcessMovements(ctx, solanaApp.InitialAssetMovementTransfer, expectedTransfers, actualTransfers, solBalance) + if err != nil { + return err + } + err = node.comparePostProcessMovements(ctx, solanaApp.InitialAssetMovementBurn, expectedBurns, actualBurns, nil) + if err != nil { + return err + } return nil } @@ -720,47 +897,239 @@ func (node *Node) compareDepositCallWithSolanaTx(ctx context.Context, tx *solana panic(err) } - transfers = nil - for _, ix := range tx.Message.Instructions { - if transfer := solanaApp.ExtractInitialTransfersFromInstruction(&tx.Message, ix); transfer != nil { - transfers = append(transfers, transfer) - } + actualTransfers, actualBurns, err := buildInitialAssetMovementMaps(tx, user, "") + if err != nil { + return err + } + // Deposits are generated per receiver, while expectedChanges is keyed as + // receiver:mint. Filter to this user before splitting transfer and burn. + expectedTransfers, expectedBurns := node.collectExpectedDepositMovements(ctx, expectedChanges, user) + err = node.compareDepositMovements(ctx, signature, tx, solanaApp.InitialAssetMovementTransfer, expectedTransfers, actualTransfers) + if err != nil { + return err } - actualChanges := make(map[string]*big.Int) - for _, t := range transfers { - if t.Sender != user { + err = node.compareDepositMovements(ctx, signature, tx, solanaApp.InitialAssetMovementBurn, expectedBurns, actualBurns) + if err != nil { + return err + } + return nil +} + +func (node *Node) collectExpectedDepositMovements(ctx context.Context, expectedChanges map[string]*big.Int, user string) (map[string]*big.Int, map[string]*big.Int) { + expectedTransfers := make(map[string]*big.Int) + expectedBurns := make(map[string]*big.Int) + changes := filterExpectedDepositChangesByUser(expectedChanges, user) + for address, expected := range changes { + if node.shouldSkipExpectedDepositMovement(ctx, address, expected) { continue } - key := fmt.Sprintf("%s:%s", t.Sender, t.TokenAddress) - total := actualChanges[key] - if total != nil { - actualChanges[key] = new(big.Int).Add(total, t.Value) - } else { - actualChanges[key] = t.Value + + expectedMap := expectedTransfers + if node.isDeployedAssetAddress(ctx, address) { + expectedMap = expectedBurns } + expectedMap[address] = addBigInt(expectedMap[address], expected) } + return expectedTransfers, expectedBurns +} + +func filterExpectedDepositChangesByUser(expectedChanges map[string]*big.Int, user string) map[string]*big.Int { + changes := make(map[string]*big.Int) for key, expected := range expectedChanges { - address := strings.Split(key, ":")[1] - if address == solanaApp.SolanaEmptyAddress && expected.Uint64() < 10 { + receiver, address, ok := strings.Cut(key, ":") + if !ok || receiver != user { continue } - isNFT, err := node.RPCCheckNFT(ctx, address) - if err != nil { - panic(fmt.Errorf("node.RPCCheckNFT(%s) => %v", address, err)) - } else if isNFT { + changes[address] = addBigInt(changes[address], expected) + } + return changes +} + +func (node *Node) shouldSkipExpectedDepositMovement(ctx context.Context, address string, expected *big.Int) bool { + if address == solanaApp.SolanaEmptyAddress && expected.Uint64() < 10 { + return true + } + isNFT, err := node.RPCCheckNFT(ctx, address) + if err != nil { + panic(fmt.Errorf("node.RPCCheckNFT(%s) => %v", address, err)) + } + return isNFT +} + +func addExpectedSystemCallMovement(m map[string]*ReferencedTxAsset, asset *ReferencedTxAsset) { + old := m[asset.Address] + if old != nil { + old.Amount = old.Amount.Add(asset.Amount) + return + } + copy := *asset + m[asset.Address] = © +} + +func buildInitialAssetMovementMaps(tx *solana.Transaction, includeSender, excludeSender string) (map[string]*solanaApp.InitialAssetMovement, map[string]*solanaApp.InitialAssetMovement, error) { + transfers := make(map[string]*solanaApp.InitialAssetMovement) + burns := make(map[string]*solanaApp.InitialAssetMovement) + decimals := make(map[string]uint8) + for _, movement := range solanaApp.ExtractInitialAssetMovements(tx) { + if includeSender != "" && movement.Sender != includeSender { + continue + } + if excludeSender != "" && movement.Sender == excludeSender { + continue + } + // A mint has one precision, even across transfer and burn instructions. + // Check before aggregation can discard subsequent instruction decimals. + if previous, ok := decimals[movement.TokenAddress]; ok && previous != movement.Decimal { + return nil, nil, fmt.Errorf("inconsistent movement decimals: %s %d %d", movement.TokenAddress, previous, movement.Decimal) + } + decimals[movement.TokenAddress] = movement.Decimal + target := transfers + if movement.Kind == solanaApp.InitialAssetMovementBurn { + target = burns + } + old := target[movement.TokenAddress] + if old == nil { + copy := *movement + copy.Value = new(big.Int).Set(movement.Value) + target[movement.TokenAddress] = © + continue + } + old.Value = addBigInt(old.Value, movement.Value) + } + return transfers, burns, nil +} + +func (node *Node) comparePostProcessMovements(ctx context.Context, kind solanaApp.InitialAssetMovementKind, expected map[string]*ReferencedTxAsset, actual map[string]*solanaApp.InitialAssetMovement, solBalance *uint64) error { + for address, asset := range expected { + if node.shouldSkipPostProcessMovement(ctx, address, asset.Amount) { continue } - actual := actualChanges[key] - if actual == nil { - return fmt.Errorf("non-existed deposit: %s %s %s", signature, key, tx.MustToBase64()) + expectedValue := asset.Amount.Mul(decimal.New(1, int32(asset.Decimal))).BigInt() + movement := actual[address] + if movement == nil { + if kind == solanaApp.InitialAssetMovementTransfer && address == solanaApp.SolanaEmptyAddress { + if isSOLCleanupDust(asset.AssetId, decimal.NewFromBigInt(expectedValue, 0)) { + continue + } + if solBalance == nil || !expectedValue.IsUint64() { + return fmt.Errorf("missing or invalid SOL cleanup balance") + } + unsafe, err := isSOLCleanupRentUnsafe(*solBalance, expectedValue.Uint64()) + if err != nil { + return err + } + if unsafe { + continue + } + } + return fmt.Errorf("missing %s user balance change: %s", kind, address) } - if actual.Cmp(expected) != 0 { - return fmt.Errorf("invalid deposit: %s %s %s %s %s", signature, key, expected.String(), actual.String(), tx.MustToBase64()) + if movement.Value.Cmp(expectedValue) != 0 { + actualAmount := decimal.NewFromBigInt(movement.Value, -int32(movement.Decimal)) + return fmt.Errorf("invalid %s user balance change: %s %s %s", kind, address, actualAmount.String(), asset.Amount.String()) + } + } + for address, movement := range actual { + asset := expected[address] + // Validate before dust/NFT exemptions use the instruction precision. + if asset != nil && int(movement.Decimal) != asset.Decimal { + return fmt.Errorf("invalid %s user balance change decimals: %s %d %d", kind, address, movement.Decimal, asset.Decimal) + } + if kind == solanaApp.InitialAssetMovementTransfer && address == solanaApp.SolanaEmptyAddress { + if solBalance == nil || !movement.Value.IsUint64() { + return fmt.Errorf("missing or invalid SOL cleanup balance") + } + unsafe, err := isSOLCleanupRentUnsafe(*solBalance, movement.Value.Uint64()) + if err != nil { + return err + } + if unsafe { + return fmt.Errorf("SOL cleanup leaves insufficient rent") + } + if asset == nil || movement.Value.Cmp(asset.Amount.Shift(int32(asset.Decimal)).BigInt()) != 0 { + return fmt.Errorf("unexpected SOL cleanup amount: %s", movement.Value) + } + } + amount := decimal.NewFromBigInt(movement.Value, -int32(movement.Decimal)) + if node.shouldSkipPostProcessMovement(ctx, address, amount) { + continue + } + if asset == nil { + return fmt.Errorf("unexpected %s user balance change: %s %s", kind, address, amount.String()) + } + // A skipped expectation (including zero or negative) does not authorize + // an actual movement merely because its asset remains in the ledger. + expectedValue := asset.Amount.Shift(int32(asset.Decimal)).BigInt() + if movement.Value.Cmp(expectedValue) != 0 { + return fmt.Errorf("invalid %s user balance change: %s %s %s", kind, address, amount.String(), asset.Amount.String()) } } return nil } +func (node *Node) shouldSkipPostProcessMovement(ctx context.Context, address string, amount decimal.Decimal) bool { + dust := decimal.RequireFromString("0.00000001") + if amount.Cmp(dust) < 0 { + return true + } + + isNFT, err := node.RPCCheckNFT(ctx, address) + if err != nil { + panic(fmt.Errorf("node.RPCCheckNFT(%s) => %v", address, err)) + } + return isNFT +} + +func (node *Node) compareDepositMovements(ctx context.Context, signature string, tx *solana.Transaction, kind solanaApp.InitialAssetMovementKind, expected map[string]*big.Int, actual map[string]*solanaApp.InitialAssetMovement) error { + for address, amount := range expected { + movement := actual[address] + if movement == nil { + return fmt.Errorf("non-existed %s deposit: %s %s %s", kind, signature, address, tx.MustToBase64()) + } + if movement.Value.Cmp(amount) != 0 { + return fmt.Errorf("invalid %s deposit: %s %s %s %s %s", kind, signature, address, amount.String(), movement.Value.String(), tx.MustToBase64()) + } + } + for address, movement := range actual { + if expected[address] == nil { + if node.shouldSkipDepositMovement(ctx, address, movement.Value) { + continue + } + return fmt.Errorf("unexpected %s deposit: %s %s %s %s", kind, signature, address, movement.Value.String(), tx.MustToBase64()) + } + } + return nil +} + +func (node *Node) shouldSkipDepositMovement(ctx context.Context, address string, value *big.Int) bool { + if address == solanaApp.SolanaEmptyAddress && value.Uint64() < 10 { + return true + } + isNFT, err := node.RPCCheckNFT(ctx, address) + if err != nil { + panic(fmt.Errorf("node.RPCCheckNFT(%s) => %v", address, err)) + } + return isNFT +} + +func (node *Node) isDeployedAssetAddress(ctx context.Context, address string) bool { + if address == solanaApp.SolanaEmptyAddress { + return false + } + da, err := node.store.ReadDeployedAssetByAddress(ctx, address) + if err != nil { + panic(fmt.Errorf("store.ReadDeployedAssetByAddress(%s) => %v", address, err)) + } + return da != nil +} + +func addBigInt(a, b *big.Int) *big.Int { + if a == nil { + return new(big.Int).Set(b) + } + return new(big.Int).Add(a, b) +} + func attachSystemCall(extra []byte, cid string, raw []byte) []byte { extra = append(extra, uuid.Must(uuid.FromString(cid)).Bytes()...) extra = append(extra, raw...) diff --git a/store/call.go b/store/call.go index fb2e7cc..0e973df 100644 --- a/store/call.go +++ b/store/call.go @@ -630,13 +630,13 @@ func (s *SQLite3Store) CheckUnfinishedSubCalls(ctx context.Context, call *System s.mutex.RLock() defer s.mutex.RUnlock() - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return false, err + query := "SELECT 1 FROM system_calls WHERE superior_id=? AND state=? AND call_type=? LIMIT 1" + var exists int + err := s.db.QueryRowContext(ctx, query, call.RequestId, common.RequestStatePending, CallTypePrepare).Scan(&exists) + if err == sql.ErrNoRows { + return false, nil } - defer common.Rollback(tx) - - return s.checkExistence(ctx, tx, "SELECT id FROM system_calls WHERE call_type=? AND state=? AND superior_id=?", CallTypePrepare, common.RequestStatePending, call.RequestId) + return err == nil, err } func (s *SQLite3Store) CheckUnfinishedPreviousMainCalls(ctx context.Context, call *SystemCall) (bool, error) { diff --git a/store/output.go b/store/output.go index 3b7f768..42fa853 100644 --- a/store/output.go +++ b/store/output.go @@ -9,6 +9,7 @@ import ( "github.com/MixinNetwork/bot-api-go-client/v3" "github.com/MixinNetwork/safe/common" + "github.com/MixinNetwork/safe/mtg" ) type UserOutput struct { @@ -62,6 +63,42 @@ func (s *SQLite3Store) WriteUserDepositWithRequest(ctx context.Context, req *Req return tx.Commit() } +// Refund references rejected before a system call locks them. A compaction +// result has no refund transactions, so keep the deposits available for retry. +func (s *SQLite3Store) RefundUserDepositsWithRequest(ctx context.Context, req *Request, outputs []*UserOutput, txs []*mtg.Transaction, compaction string) error { + s.mutex.Lock() + defer s.mutex.Unlock() + + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer common.Rollback(tx) + + if compaction == "" { + for _, output := range outputs { + err = s.execOne(ctx, tx, "UPDATE user_outputs SET state=?, updated_at=? WHERE output_id=? AND user_id=? AND state=? AND signed_by IS NULL", + common.RequestStateFailed, req.CreatedAt, output.OutputId, output.UserId, common.RequestStateInitial) + if err != nil { + return fmt.Errorf("refund user output %s: %w", output.OutputId, err) + } + } + } + + err = s.failRequest(ctx, tx, req, txs, compaction) + if err != nil { + return err + } + + if compaction == "" && len(txs) > 0 { + if err := s.writeNotifications(ctx, tx, txs); err != nil { + return err + } + } + + return tx.Commit() +} + func (s *SQLite3Store) ListUserOutputsByHashAndState(ctx context.Context, user_id, hash string, state byte) ([]*UserOutput, error) { vals := []any{user_id, hash} query := fmt.Sprintf("SELECT %s FROM user_outputs WHERE user_id=? AND transaction_hash=?", strings.Join(userOutputCols, ","))