diff --git a/apps/solana/common.go b/apps/solana/common.go index 7796749..c269efc 100644 --- a/apps/solana/common.go +++ b/apps/solana/common.go @@ -17,23 +17,29 @@ import ( "github.com/blocto/solana-go-sdk/types" "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/memo" "github.com/gagliardetto/solana-go/programs/system" "github.com/gagliardetto/solana-go/programs/token" ) -var ErrTransactionTooLarge = errors.New("solana transaction too large") +var ( + ErrTransactionTooLarge = errors.New("solana transaction too large") + ErrInvalidV1Config = errors.New("invalid solana v1 transaction config") +) type transactionTooLargeError struct { encodedSize int + encodedMax int + rawMax int } func (e *transactionTooLargeError) Error() string { return fmt.Sprintf( "base64 encoded solana_transaction::versioned::VersionedTransaction too large: %d bytes (max: encoded/raw %d/%d)", e.encodedSize, - MaxTransactionEncodedSize, - MaxTransactionRawSize, + e.encodedMax, + e.rawMax, ) } @@ -46,8 +52,10 @@ const ( MintSize uint64 = 82 NormalAccountSize uint64 = 165 - MaxTransactionRawSize = 1232 - MaxTransactionEncodedSize = 1644 + MaxTransactionRawSize = 1232 + MaxTransactionEncodedSize = 1644 + MaxTransactionRawSizeV1 = solana.MaxTransactionSizeV1 + MaxTransactionEncodedSizeV1 = (MaxTransactionRawSizeV1 + 2) / 3 * 4 maxNameLength = 32 maxSymbolLength = 10 @@ -75,11 +83,58 @@ func ValidateTransactionSize(tx *solana.Transaction) error { if err != nil { return fmt.Errorf("marshal solana transaction: %w", err) } - if len(raw) <= MaxTransactionRawSize { + rawMax := MaxTransactionRawSize + if tx.Message.GetVersion() == solana.MessageVersionV1 { + rawMax = MaxTransactionRawSizeV1 + } + if len(raw) <= rawMax { return nil } - return &transactionTooLargeError{encodedSize: base64.StdEncoding.EncodedLen(len(raw))} + return &transactionTooLargeError{ + encodedSize: base64.StdEncoding.EncodedLen(len(raw)), + encodedMax: base64.StdEncoding.EncodedLen(rawMax), + rawMax: rawMax, + } +} + +// ValidateTransaction checks the message structure, wire size, and nonzero +// resource limits required for V1 execution. It does not estimate sufficient +// resources or require signatures before all parties have signed. +func ValidateTransaction(tx *solana.Transaction) error { + err := tx.Message.Sanitize() + if err != nil { + return fmt.Errorf("sanitize solana transaction message: %w", err) + } + if err := ValidateTransactionSize(tx); err != nil { + return err + } + if tx.Message.GetVersion() == solana.MessageVersionV1 { + // Unlike legacy/V0, omitted V1 resource limits default to zero. + config := tx.Message.TransactionConfig + if config.ComputeUnitLimit == nil || *config.ComputeUnitLimit == 0 { + return fmt.Errorf("%w: compute unit limit must be set and greater than zero", ErrInvalidV1Config) + } + if config.LoadedAccountsDataSizeLimit == nil || *config.LoadedAccountsDataSizeLimit == 0 { + return fmt.Errorf("%w: loaded accounts data size limit must be set and greater than zero", ErrInvalidV1Config) + } + } + return nil +} + +// ValidateWireTransaction additionally checks that a decoded or sendable +// transaction has exactly the signature slots declared by its message header. +// Zero-valued placeholder signatures remain valid for transactions awaiting +// multi-party signing. +func ValidateWireTransaction(tx *solana.Transaction) error { + if tx == nil { + return fmt.Errorf("nil solana transaction") + } + err := tx.Sanitize() + if err != nil { + return fmt.Errorf("sanitize solana wire transaction: %w", err) + } + return ValidateTransaction(tx) } type Metadata struct { @@ -183,9 +238,11 @@ func (c *Client) buildInitialTxWithNonceAccount(ctx context.Context, payer solan solana.SysVarRecentBlockHashesPubkey, payer, ).Build()) - - computerPriceIns := c.getPriorityFeeInstruction(ctx) - b.AddInstruction(computerPriceIns) + if common.CheckTestEnvironment(ctx) { + // Historical replay fixtures predate v1 and included a zero-price + // ComputeBudget instruction immediately after the nonce advance. + b.AddInstruction(computebudget.NewSetComputeUnitPriceInstruction(0).Build()) + } return b } diff --git a/apps/solana/rpc.go b/apps/solana/rpc.go index e0abbce..1cf644e 100644 --- a/apps/solana/rpc.go +++ b/apps/solana/rpc.go @@ -28,6 +28,8 @@ type Client struct { rpcEndpoint string } +const recentPrioritizationFeeMaxAttempts = 3 + type AssetMetadata struct { Symbol string `json:"symbol"` Name string `json:"name"` @@ -59,6 +61,24 @@ func (c *Client) RPCGetConfirmedHeight(ctx context.Context) (uint64, error) { } } +func (c *Client) RPCGetRecentPrioritizationFees(ctx context.Context, accounts solana.PublicKeySlice) ([]rpc.PriorizationFeeResult, error) { + for attempt := 1; attempt <= recentPrioritizationFeeMaxAttempts; attempt++ { + fees, err := c.rpcClient.GetRecentPrioritizationFees(ctx, accounts) + if err == nil { + return fees, nil + } + if attempt == recentPrioritizationFeeMaxAttempts || !mtg.CheckRetryableError(err) { + return nil, err + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(300 * time.Millisecond): + } + } + panic("unreachable") +} + func (c *Client) RPCGetBlockByHeight(ctx context.Context, height uint64) (*rpc.GetBlockResult, error) { for { block, err := c.rpcClient.GetBlockWithOpts(ctx, height, &rpc.GetBlockOpts{ @@ -361,10 +381,11 @@ func (c *Client) GetMint(ctx context.Context, mint solana.PublicKey) (*token.Min } func (c *Client) SendTransaction(ctx context.Context, tx *solana.Transaction) (string, error) { - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateWireTransaction(tx); err != nil { return "", err } sig, err := c.rpcClient.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{ + Encoding: solana.EncodingBase64, SkipPreflight: true, PreflightCommitment: rpc.CommitmentProcessed, }) diff --git a/apps/solana/transaction.go b/apps/solana/transaction.go index 2aed34f..5520585 100644 --- a/apps/solana/transaction.go +++ b/apps/solana/transaction.go @@ -3,6 +3,7 @@ package solana import ( "context" "fmt" + "math" "slices" "strings" @@ -11,7 +12,6 @@ import ( "github.com/blocto/solana-go-sdk/program/address_lookup_table" "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/memo" "github.com/gagliardetto/solana-go/programs/system" "github.com/gagliardetto/solana-go/programs/token" @@ -20,7 +20,17 @@ import ( "github.com/shopspring/decimal" ) -const solanaInnerIndexBase = int64(1_000_000_000) +const ( + solanaInnerIndexBase = int64(1_000_000_000) + + // Agave runtime limits and denomination constants: + // https://solana.com/docs/core/constants-reference + maxComputeUnitLimit = uint32(1_400_000) + // V1 defaults this limit to zero when omitted, so sets it explicitly. + maxLoadedAccountsDataSizeLimit = uint32(64 * 1024 * 1024) + microLamportsPerLamport = int64(1_000_000) + defaultMicroLamportsPerCU = uint64(1_000) +) func (c *Client) CreateNonceAccount(ctx context.Context, key, nonce string, rent uint64) (*solana.Transaction, error) { payer, err := solana.PrivateKeyFromBase58(key) @@ -32,41 +42,45 @@ func (c *Client) CreateNonceAccount(ctx context.Context, key, nonce string, rent panic(err) } - computerPriceIns := c.getPriorityFeeInstruction(ctx) block, err := c.rpcClient.GetLatestBlockhash(ctx, rpc.CommitmentProcessed) if err != nil { return nil, fmt.Errorf("solana.GetLatestBlockhash() => %v", err) } blockhash := block.Value.Blockhash + instructions := []solana.Instruction{ + system.NewCreateAccountInstruction( + rent, + NonceAccountSize, + system.ProgramID, + payer.PublicKey(), + nonceKey.PublicKey(), + ).Build(), + system.NewInitializeNonceAccountInstruction( + payer.PublicKey(), + nonceKey.PublicKey(), + solana.SysVarRecentBlockHashesPubkey, + solana.SysVarRentPubkey, + ).Build(), + } tx, err := solana.NewTransaction( - []solana.Instruction{ - system.NewCreateAccountInstruction( - rent, - NonceAccountSize, - system.ProgramID, - payer.PublicKey(), - nonceKey.PublicKey(), - ).Build(), - system.NewInitializeNonceAccountInstruction( - payer.PublicKey(), - nonceKey.PublicKey(), - solana.SysVarRecentBlockHashesPubkey, - solana.SysVarRentPubkey, - ).Build(), - computerPriceIns, - }, + instructions, blockhash, solana.TransactionPayer(payer.PublicKey()), + solana.TransactionV1Config(defaultV1TransactionConfig()), ) if err != nil { panic(err) } + err = c.configureV1Transaction(ctx, tx) + if err != nil { + return nil, err + } _, err = tx.Sign(BuildSignersGetter(nonceKey, payer)) if err != nil { panic(err) } - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateTransaction(tx); err != nil { return nil, err } return tx, nil @@ -79,33 +93,37 @@ func (c *Client) InitializeAccount(ctx context.Context, key, user string) (*sola if err != nil { return nil, fmt.Errorf("soalan.GetMinimumBalanceForRentExemption(%d) => %v", NormalAccountSize, err) } - computerPriceIns := c.getPriorityFeeInstruction(ctx) block, err := c.rpcClient.GetLatestBlockhash(ctx, rpc.CommitmentProcessed) if err != nil { return nil, fmt.Errorf("solana.GetLatestBlockhash() => %v", err) } blockhash := block.Value.Blockhash + instructions := []solana.Instruction{ + system.NewTransferInstruction( + rentExemptBalance, + payer.PublicKey(), + solana.MPK(user), + ).Build(), + } tx, err := solana.NewTransaction( - []solana.Instruction{ - system.NewTransferInstruction( - rentExemptBalance, - payer.PublicKey(), - solana.MPK(user), - ).Build(), - computerPriceIns, - }, + instructions, blockhash, solana.TransactionPayer(payer.PublicKey()), + solana.TransactionV1Config(defaultV1TransactionConfig()), ) if err != nil { panic(err) } + err = c.configureV1Transaction(ctx, tx) + if err != nil { + return nil, err + } _, err = tx.Sign(BuildSignersGetter(payer)) if err != nil { panic(err) } - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateTransaction(tx); err != nil { return nil, err } return tx, nil @@ -169,14 +187,15 @@ func (c *Client) CreateMints(ctx context.Context, payer, mtg solana.PublicKey, a ) } - computerPriceIns := c.getPriorityFeeInstruction(ctx) - builder.AddInstruction(computerPriceIns) - block, err := c.rpcClient.GetLatestBlockhash(ctx, rpc.CommitmentProcessed) if err != nil { return nil, fmt.Errorf("solana.GetLatestBlockhash() => %v", err) } builder.SetRecentBlockHash(block.Value.Blockhash) + err = c.configureV1TransactionBuilder(ctx, builder) + if err != nil { + return nil, err + } tx, err := builder.Build() if err != nil { @@ -195,7 +214,7 @@ func (c *Client) CreateMints(ctx context.Context, payer, mtg solana.PublicKey, a panic(err) } } - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateTransaction(tx); err != nil { return nil, err } return tx, nil @@ -205,16 +224,13 @@ func (c *Client) ExtendLookupTables(ctx context.Context, key, table string, as [ payer := solana.MustPrivateKeyFromBase58(key) pb := sc.PublicKeyFromString(payer.PublicKey().String()) - computerPriceIns := c.getPriorityFeeInstruction(ctx) block, err := c.rpcClient.GetLatestBlockhash(ctx, rpc.CommitmentProcessed) if err != nil { return nil, "", fmt.Errorf("solana.GetLatestBlockhash() => %v", err) } blockhash := block.Value.Blockhash - ins := []solana.Instruction{ - computerPriceIns, - } + var ins []solana.Instruction if table == "" { instruction, t := BuildCreateAddressLookupTableInstruction(block, pb) table = t @@ -233,21 +249,51 @@ func (c *Client) ExtendLookupTables(ctx context.Context, key, table string, as [ ins, blockhash, solana.TransactionPayer(payer.PublicKey()), + solana.TransactionV1Config(defaultV1TransactionConfig()), ) if err != nil { panic(err) } + err = c.configureV1Transaction(ctx, tx) + if err != nil { + return nil, "", err + } _, err = tx.Sign(BuildSignersGetter(payer)) if err != nil { panic(err) } - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateTransaction(tx); err != nil { return nil, "", err } return tx, table, nil } func (c *Client) TransferOrMintTokens(ctx context.Context, payer, mtg solana.PublicKey, nonce NonceAccount, transfers []*TokenTransfer, memoStr string) (*solana.Transaction, error) { + builder, err := c.NewTransferOrMintTokensBuilder(ctx, payer, mtg, nonce, transfers, memoStr) + if err != nil { + return nil, err + } + err = c.configureV1TransactionBuilder(ctx, builder) + if err != nil { + return nil, err + } + + tx, err := builder.Build() + if err != nil { + panic(err) + } + err = ValidateTransaction(tx) + if err != nil { + return nil, err + } + return tx, nil +} + +// NewTransferOrMintTokensBuilder builds the durable-nonce and asset +// instructions without selecting a transaction version or estimating its v1 +// resource configuration. Cleanup verification uses this to rebuild the +// signed business instructions without consulting a current priority-fee quote. +func (c *Client) NewTransferOrMintTokensBuilder(ctx context.Context, payer, mtg solana.PublicKey, nonce NonceAccount, transfers []*TokenTransfer, memoStr string) (*solana.TransactionBuilder, error) { builder := c.buildInitialTxWithNonceAccount(ctx, payer, nonce) for _, transfer := range transfers { @@ -290,18 +336,33 @@ func (c *Client) TransferOrMintTokens(ctx context.Context, payer, mtg solana.Pub ).Build(), ) } + return builder, nil +} + +func (c *Client) TransferOrBurnTokens(ctx context.Context, payer, user solana.PublicKey, nonce NonceAccount, transfers []*TokenTransfer) (*solana.Transaction, error) { + builder, err := c.NewTransferOrBurnTokensBuilder(ctx, payer, user, nonce, transfers) + if err != nil { + return nil, err + } + err = c.configureV1TransactionBuilder(ctx, builder) + if err != nil { + return nil, err + } tx, err := builder.Build() if err != nil { panic(err) } - if err := ValidateTransactionSize(tx); err != nil { + if err := ValidateTransaction(tx); err != nil { return nil, err } return tx, nil } -func (c *Client) TransferOrBurnTokens(ctx context.Context, payer, user solana.PublicKey, nonce NonceAccount, transfers []*TokenTransfer) (*solana.Transaction, error) { +// NewTransferOrBurnTokensBuilder is the burn-side counterpart to +// NewTransferOrMintTokensBuilder. It only builds the deterministic transaction +// instructions; callers decide how the final transaction is configured. +func (c *Client) NewTransferOrBurnTokensBuilder(ctx context.Context, payer, user solana.PublicKey, nonce NonceAccount, transfers []*TokenTransfer) (*solana.TransactionBuilder, error) { builder := c.buildInitialTxWithNonceAccount(ctx, payer, nonce) for _, transfer := range transfers { @@ -326,15 +387,7 @@ func (c *Client) TransferOrBurnTokens(ctx context.Context, payer, user solana.Pu ).Build(), ) } - - tx, err := builder.Build() - if err != nil { - return nil, err - } - if err := ValidateTransactionSize(tx); err != nil { - return nil, err - } - return tx, nil + return builder, nil } func (c *Client) AddTransferSolanaAssetInstruction(ctx context.Context, builder *solana.TransactionBuilder, transfer *TokenTransfer, payer, source solana.PublicKey) (*solana.TransactionBuilder, error) { @@ -404,27 +457,93 @@ func (c *Client) AddTransferSolanaAssetInstruction(ctx context.Context, builder return builder, nil } -func (c *Client) getPriorityFeeInstruction(ctx context.Context) *computebudget.Instruction { +// defaultV1TransactionConfig reserves bounded resources without simulating +// against current account state. Prepares are built before their funding +// withdrawals, and other transactions may execute against different state. +// V1 requires explicit nonzero compute and loaded-account limits. +func defaultV1TransactionConfig() solana.TransactionConfig { + return solana.TransactionConfig{}. + WithComputeUnitLimit(maxComputeUnitLimit). + WithLoadedAccountsDataSizeLimit(maxLoadedAccountsDataSizeLimit). + WithPriorityFee(0) +} + +func (c *Client) getV1TransactionConfig(ctx context.Context, tx *solana.Transaction) (solana.TransactionConfig, error) { + config := defaultV1TransactionConfig() + if common.CheckTestEnvironment(ctx) { + return config, nil + } + + writableAccounts, err := tx.Message.Writable() + if err != nil { + return solana.TransactionConfig{}, fmt.Errorf("solana.Message.Writable() => %w", err) + } + recentFees, err := c.RPCGetRecentPrioritizationFees(ctx, writableAccounts) + if err != nil { + return solana.TransactionConfig{}, fmt.Errorf("solana.GetRecentPrioritizationFees() => %w", err) + } + microLamportsPerCU := getMedianPriorityFee(recentFees) + priorityFee := getTotalPriorityFee(microLamportsPerCU, maxComputeUnitLimit) + + return config.WithPriorityFee(priorityFee), nil +} + +func (c *Client) configureV1Transaction(ctx context.Context, tx *solana.Transaction) error { + config, err := c.getV1TransactionConfig(ctx, tx) + if err != nil { + return err + } + tx.Message.TransactionConfig = config + return nil +} + +func (c *Client) configureV1TransactionBuilder(ctx context.Context, builder *solana.TransactionBuilder) error { + // Computer's offline replay tests compare transactions with historical + // legacy messages and synthetic nonce state. Preserve those message bytes. if common.CheckTestEnvironment(ctx) { - return computebudget.NewSetComputeUnitPriceInstruction(0).Build() + return nil } - recentFees, err := c.rpcClient.GetRecentPrioritizationFees(ctx, []solana.PublicKey{}) + + builder.SetTransactionConfig(defaultV1TransactionConfig()) + preview, err := builder.Build() if err != nil { - panic(err) + return err } - fee := getAveragePriorityFee(recentFees) - return computebudget.NewSetComputeUnitPriceInstruction(fee).Build() + config, err := c.getV1TransactionConfig(ctx, preview) + if err != nil { + return err + } + builder.SetTransactionConfig(config) + return nil } -func getAveragePriorityFee(recentFees []rpc.PriorizationFeeResult) uint64 { +func getTotalPriorityFee(microLamportsPerCU uint64, computeUnitLimit uint32) uint64 { + fee := decimal.NewFromUint64(microLamportsPerCU). + Mul(decimal.NewFromUint64(uint64(computeUnitLimit))). + Div(decimal.NewFromInt(microLamportsPerLamport)). + RoundCeil(0) + // Saturate only at the wire format's uint64 limit, without a service fee cap. + if !fee.BigInt().IsUint64() { + return math.MaxUint64 + } + return fee.BigInt().Uint64() +} + +func getMedianPriorityFee(recentFees []rpc.PriorizationFeeResult) uint64 { if len(recentFees) == 0 { - return 1000 + return defaultMicroLamportsPerCU + } + fees := make([]uint64, len(recentFees)) + for i, fee := range recentFees { + fees[i] = fee.PrioritizationFee } - total := decimal.NewFromInt(0) - for _, fee := range recentFees { - total = total.Add(decimal.NewFromUint64(fee.PrioritizationFee)) + slices.Sort(fees) + middle := len(fees) / 2 + if len(fees)%2 == 1 { + return fees[middle] } - return total.Div(decimal.NewFromInt(int64(len(recentFees)))).BigInt().Uint64() + lower, upper := fees[middle-1], fees[middle] + return lower + (upper-lower)/2 } func ExtractTransfersFromTransaction(ctx context.Context, tx *solana.Transaction, meta *rpc.TransactionMeta, exception *solana.PublicKey) ([]*Transfer, error) { diff --git a/solana/observer.go b/solana/observer.go index 7a31d42..38fc7bc 100644 --- a/solana/observer.go +++ b/solana/observer.go @@ -759,13 +759,13 @@ func (node *Node) handleSignedCallSequence(ctx context.Context, wg *sync.WaitGro if err != nil { panic(fmt.Errorf("solana.TransactionFromBase64(%s) => %v", c.RequestId, err)) } - err = solanaApp.ValidateTransactionSize(tx) + err = solanaApp.ValidateWireTransaction(tx) if errors.Is(err, solanaApp.ErrTransactionTooLarge) { logger.Printf("node.handleSignedCallSequence(%s) => skip oversized call %s: %v", key, c.RequestId, err) return } if err != nil { - panic(fmt.Errorf("solana.ValidateTransactionSize(%s) => %v", c.RequestId, err)) + panic(fmt.Errorf("solana.ValidateWireTransaction(%s) => %v", c.RequestId, err)) } } logger.Printf("node.handleSignedCallSequence(%s) => %s", key, strings.Join(ids, ",")) diff --git a/solana/request.go b/solana/request.go index c8cc9cc..f559b96 100644 --- a/solana/request.go +++ b/solana/request.go @@ -7,6 +7,7 @@ import ( "strings" "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/mixin/logger" @@ -113,7 +114,14 @@ func validateConfirmCallStorage(storage []byte) error { if err != nil { return fmt.Errorf("invalid post call id: %v", err) } - _, err = solana.TransactionFromBytes(storage[uuid.Size:]) + tx, err := solana.TransactionFromBytes(storage[uuid.Size:]) + if err != nil { + return fmt.Errorf("invalid post call transaction: %v", err) + } + // Defensive validation: the observer builds and validates this transaction + // before attaching it, so a correctly functioning observer using compatible + // validation rules should already produce a valid wire transaction. + err = solanaApp.ValidateWireTransaction(tx) if err != nil { return fmt.Errorf("invalid post call transaction: %v", err) } diff --git a/solana/solana.go b/solana/solana.go index c67597c..accef34 100644 --- a/solana/solana.go +++ b/solana/solana.go @@ -504,6 +504,10 @@ func (node *Node) CreatePrepareTransaction(ctx context.Context, call *store.Syst } func (node *Node) CreatePostProcessTransaction(ctx context.Context, call *store.SystemCall, nonce *store.NonceAccount, tx *solana.Transaction, meta *rpc.TransactionMeta) *solana.Transaction { + return node.createPostProcessTransaction(ctx, call, nonce, tx, meta, nil) +} + +func (node *Node) createPostProcessTransaction(ctx context.Context, call *store.SystemCall, nonce *store.NonceAccount, source *solana.Transaction, meta *rpc.TransactionMeta, comparison *solana.Transaction) *solana.Transaction { os, _, err := node.GetSystemCallReferenceOutputs(ctx, call.UserIdFromPublicPath(), call.RequestHash, systemCallReferenceOutputStateValue(call.State)) if err != nil { panic(fmt.Errorf("node.GetSystemCallReferenceTxs(%s) => %v", call.RequestId, err)) @@ -520,8 +524,8 @@ func (node *Node) CreatePostProcessTransaction(ctx context.Context, call *store. } user := node.getUserSolanaPublicKeyFromCall(ctx, call) - if tx != nil && meta != nil { - changes := node.buildUserBalanceChangesFromMeta(ctx, tx, meta, user) + if source != nil && meta != nil { + changes := node.buildUserBalanceChangesFromMeta(ctx, source, meta, user) for address, change := range changes { old := assets[address] if old != nil { @@ -601,7 +605,18 @@ func (node *Node) CreatePostProcessTransaction(ctx context.Context, call *store. return nil } - tx, err = node.solana.TransferOrBurnTokens(ctx, node.SolanaPayer(), user, nonce.Account(), transfers) + if comparison == nil { + tx, err := node.solana.TransferOrBurnTokens(ctx, node.SolanaPayer(), user, nonce.Account(), transfers) + if err != nil { + panic(err) + } + return tx + } + builder, err := node.solana.NewTransferOrBurnTokensBuilder(ctx, node.SolanaPayer(), user, nonce.Account(), transfers) + if err != nil { + panic(err) + } + tx, err := buildCleanupTransactionForComparison(builder, comparison) if err != nil { panic(err) } @@ -609,18 +624,62 @@ func (node *Node) CreatePostProcessTransaction(ctx context.Context, call *store. } func (node *Node) CreateRefundWithdrawalTransaction(ctx context.Context, prepare, call *store.SystemCall, nonce *store.NonceAccount) *solana.Transaction { + return node.createRefundWithdrawalTransaction(ctx, prepare, call, nonce, nil) +} + +func (node *Node) createRefundWithdrawalTransaction(ctx context.Context, prepare, call *store.SystemCall, nonce *store.NonceAccount, comparison *solana.Transaction) *solana.Transaction { transfers := node.buildRefundWithdrawalTransfers(ctx, prepare, call) if len(transfers) == 0 { return nil } - tx, err := node.solana.TransferOrMintTokens(ctx, node.SolanaPayer(), node.getMTGAddress(ctx), nonce.Account(), transfers, prepare.RequestId) + if comparison == nil { + tx, err := node.solana.TransferOrMintTokens(ctx, node.SolanaPayer(), node.getMTGAddress(ctx), nonce.Account(), transfers, prepare.RequestId) + if err != nil { + panic(err) + } + return tx + } + builder, err := node.solana.NewTransferOrMintTokensBuilder(ctx, node.SolanaPayer(), node.getMTGAddress(ctx), nonce.Account(), transfers, prepare.RequestId) + if err != nil { + panic(err) + } + tx, err := buildCleanupTransactionForComparison(builder, comparison) if err != nil { panic(err) } return tx } +// buildCleanupTransactionForComparison compiles rebuilt cleanup instructions +// with the version and inline v1 configuration already committed to by the +// transaction under review. It intentionally performs no simulation or fee +// lookup; those values can change between creation and verification. +func buildCleanupTransactionForComparison(builder *solana.TransactionBuilder, comparison *solana.Transaction) (*solana.Transaction, error) { + if comparison == nil { + return nil, fmt.Errorf("nil cleanup comparison transaction") + } + switch version := comparison.Message.GetVersion(); version { + case solana.MessageVersionLegacy: + builder.SetVersion(solana.MessageVersionLegacy) + case solana.MessageVersionV0: + builder.SetVersion(solana.MessageVersionV0) + case solana.MessageVersionV1: + builder.SetTransactionConfig(comparison.Message.TransactionConfig) + default: + return nil, fmt.Errorf("unsupported cleanup transaction version: %d", version) + } + + tx, err := builder.Build() + if err != nil { + return nil, fmt.Errorf("build cleanup comparison transaction: %w", err) + } + if err := solanaApp.ValidateTransaction(tx); err != nil { + return nil, err + } + return tx, nil +} + func (node *Node) buildRefundWithdrawalTransfers(ctx context.Context, prepare, call *store.SystemCall) []*solanaApp.TokenTransfer { withdrawals := call.GetWithdrawalIds() // the failure of prepare call means that only Solana assets are withdrawn diff --git a/solana/solana_test.go b/solana/solana_test.go index 5b09533..55e3bcb 100644 --- a/solana/solana_test.go +++ b/solana/solana_test.go @@ -119,14 +119,16 @@ func TestCreateV1(t *testing.T) { } rpcClient := solanaApp.NewClient(rpc) - mint := solana.MustPrivateKeyFromBase58("bH2GaiFeQVbPKitvweDD9ae8i2peb6QohWZTxBRJKP37siCsWte8HAd9uvbP7dqsL25HUWSDuFKfnPjAyydTnJC") + // Use a fresh mint for each transaction built by this test. + mint, err := solana.NewRandomPrivateKey() + require.NoError(err) tx, err := rpcClient.CreateMints( ctx, solana.MPK("5ECPyQVa9gZuig8guSmofttMfYjCMRxqa6nCciFTrsTB"), solana.MPK("5v1eqBfJQkX4JYCi43v7eApXERTNakRBJX1d6Ax6KRzK"), []*solanaApp.DeployedAsset{ { - Address: "AnF3RoYAxAETRPAddDWtMET5wL83uzEmbUjkHE93zsHS", + Address: mint.PublicKey().String(), Uri: "https://kernel.mixin.dev/objects/9cfd190f6d87070dac3db4209f4f1db8925a59f668e2befd7b8f4c43927526e6", Asset: &bot.AssetNetwork{ Name: "amituofo2", @@ -151,6 +153,9 @@ func TestCreateIdempotent(t *testing.T) { require := require.New(t) ctx := context.Background() rpc1 := testRpcEndpoint + if endpoint := os.Getenv("SOLANARPC"); endpoint != "" { + rpc1 = endpoint + } c := solanaApp.NewClient(rpc1) blockhash := solana.MustHashFromBase58("2fGgNDhkTwhBH1PqS6xpgmKSCSVdYUGuZBMCSQoAMRDt") diff --git a/solana/system_call.go b/solana/system_call.go index 9b411ee..e8d0933 100644 --- a/solana/system_call.go +++ b/solana/system_call.go @@ -18,6 +18,7 @@ import ( "github.com/MixinNetwork/mixin/logger" "github.com/MixinNetwork/safe/common" "github.com/gagliardetto/solana-go" + computebudget "github.com/gagliardetto/solana-go/programs/compute-budget" "github.com/gofrs/uuid/v5" "github.com/shopspring/decimal" ) @@ -384,9 +385,9 @@ func (node *Node) verifyFailedPostProcessCall(ctx context.Context, call, main, p var expected *solana.Transaction switch call.Type { case store.CallTypeMain: - expected = node.CreatePostProcessTransaction(ctx, main, nonce, nil, nil) + expected = node.createPostProcessTransaction(ctx, main, nonce, nil, nil, actual) case store.CallTypePrepare: - expected = node.CreateRefundWithdrawalTransaction(ctx, call, main, nonce) + expected = node.createRefundWithdrawalTransaction(ctx, call, main, nonce, actual) default: return fmt.Errorf("invalid failed post-process superior type: %s", call.Type) } @@ -406,12 +407,25 @@ func compareCleanupTransactions(actual, expected *solana.Transaction) error { if !slices.Equal(actual.Message.Signers(), expected.Message.Signers()) { return fmt.Errorf("invalid cleanup signers: %v", actual.Message.Signers()) } - if len(actual.Message.Instructions) != len(expected.Message.Instructions) { - return fmt.Errorf("invalid cleanup instruction count: %d %d", len(actual.Message.Instructions), len(expected.Message.Instructions)) + err := compareCleanupV1Config(actual, expected) + if err != nil { + return err + } + + actualInstructions, err := cleanupInstructions(actual) + if err != nil { + return err + } + expectedInstructions, err := cleanupInstructions(expected) + if err != nil { + return err + } + if len(actualInstructions) != len(expectedInstructions) { + return fmt.Errorf("invalid cleanup instruction count: %d %d", len(actualInstructions), len(expectedInstructions)) } - for i, actualIx := range actual.Message.Instructions { - expectedIx := expected.Message.Instructions[i] + for i, actualIx := range actualInstructions { + expectedIx := expectedInstructions[i] actualProgram, err := actual.Message.Program(actualIx.ProgramIDIndex) if err != nil { return fmt.Errorf("resolve cleanup program %d: %w", i, err) @@ -442,12 +456,6 @@ func compareCleanupTransactions(actual, expected *solana.Transaction) error { } } - if i == 1 && actualProgram == solana.ComputeBudget { - if len(actualIx.Data) != 9 || len(expectedIx.Data) != 9 || actualIx.Data[0] != expectedIx.Data[0] { - return fmt.Errorf("invalid compute budget instruction") - } - continue - } if !bytes.Equal(actualIx.Data, expectedIx.Data) { return fmt.Errorf("invalid cleanup instruction data: %d", i) } @@ -455,6 +463,42 @@ func compareCleanupTransactions(actual, expected *solana.Transaction) error { return nil } +func compareCleanupV1Config(actual, expected *solana.Transaction) error { + if actual.Message.GetVersion() != solana.MessageVersionV1 { + return nil + } + if expected.Message.GetVersion() != solana.MessageVersionV1 { + return fmt.Errorf("invalid cleanup transaction version") + } + + return nil +} + +// cleanupInstructions removes the legacy priority-fee instruction so cleanup +// calls created before the v1 rollout can still be verified after deployment. +func cleanupInstructions(tx *solana.Transaction) ([]solana.CompiledInstruction, error) { + instructions := make([]solana.CompiledInstruction, 0, len(tx.Message.Instructions)) + foundPriorityFee := false + for i, instruction := range tx.Message.Instructions { + program, err := tx.Message.Program(instruction.ProgramIDIndex) + if err != nil { + return nil, fmt.Errorf("resolve cleanup program %d: %w", i, err) + } + if program != solana.ComputeBudget { + instructions = append(instructions, instruction) + continue + } + if tx.Message.GetVersion() == solana.MessageVersionV1 || + foundPriorityFee || + len(instruction.Data) != 9 || + instruction.Data[0] != computebudget.Instruction_SetComputeUnitPrice { + return nil, fmt.Errorf("invalid compute budget instruction") + } + foundPriorityFee = true + } + return instructions, nil +} + func (node *Node) getSubSystemCallFromExtra(ctx context.Context, req *store.Request, data []byte) (*store.SystemCall, *solana.Transaction, error) { if len(data) < 16 { return nil, nil, nil @@ -472,9 +516,9 @@ func (node *Node) buildSystemCallFromBytes(ctx context.Context, req *store.Reque if err != nil { return nil, nil, err } - err = solanaApp.ValidateTransactionSize(tx) + err = solanaApp.ValidateWireTransaction(tx) if err != nil { - logger.Printf("solana.ValidateTransactionSize(%s %s) => %v", req.Id, id, err) + logger.Printf("solana.ValidateWireTransaction(%s %s) => %v", req.Id, id, err) return nil, nil, err } err = node.processTransactionWithAddressLookups(ctx, tx)