Skip to content
Merged
68 changes: 68 additions & 0 deletions apps/solana/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down
572 changes: 572 additions & 0 deletions solana/call_test.go

Large diffs are not rendered by default.

61 changes: 54 additions & 7 deletions solana/computer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"os"
Expand All @@ -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"
Expand Down Expand Up @@ -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{{
Expand Down Expand Up @@ -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]},
Expand Down Expand Up @@ -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{
Expand Down
35 changes: 31 additions & 4 deletions solana/mvm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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, "")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion solana/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package solana

import (
"context"
"database/sql"
"encoding/base64"
"encoding/binary"
"errors"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading