Derive the Solana token recipient account locally
What changed, and why it matters
This commit fixes a bug in Stack Wallet's Solana token transfers. Previously, the wallet asked the blockchain node to find the recipient's token account, and only checked that it was a valid token account—not that it actually belonged to the intended recipient. A malicious or compromised node could have returned any other holder's account for the same token, causing the user's payment to be sent to the wrong person. The fix always calculates the recipient's token address locally from their wallet address and the token type, so the destination cannot be manipulated by the node. The self-transfer detection was also corrected to compare recipient wallet addresses rather than token account addresses.
Treat this as a security fix. Ensure the updated version is released promptly and users are encouraged to upgrade before sending Solana token transactions, especially when connected to untrusted or third-party RPC nodes. Review other wallet code paths that rely on RPC-reported accounts for destination selection.
Security signals we found
Removal of RPC-reported destination token account selection
Local derivation of Associated Token Account (ATA) from recipient owner address
Test explicitly models hostile node returning decoy account for same mint
Self-transfer detection changed from token account equality to owner address equality
Commit message describes security-relevant threat model: hostile node
Evidence from the diff
The patch removes _findOrDeriveRecipientTokenAccount(), which queried getTokenAccountsByOwner and could return an arbitrary token account for the same mint. It replaces that path with local derivation via _deriveAtaAddress() using the recipient’s owner address, mint, and token program ID. The previous code only validated the returned account against the System Program, not the owner. The self-transfer check now compares txData.recipients!.first.address == walletAddress instead of comparing derived token account strings, which is more semantically correct. A test was added simulating a hostile node returning a decoy token account and asserting the destination remains the recipient’s derived ATA.
Changed components
lib/wallets/wallet/impl/sub_wallets/solana_token_wallet.dartSolana SPL / Token-2022 token transfer preparationRPC client interaction for recipient token account lookupInspect captured patch +35 / −72
### lib/wallets/wallet/impl/sub_wallets/solana_token_wallet.dart
@@ -141,21 +141,15 @@ class SolanaTokenWallet extends Wallet {
await rpcClient.getLatestBlockhash();
- final recipientTokenAccount = await _findOrDeriveRecipientTokenAccount(
- recipientAddress: recipientAddress,
+ // Derive the destination locally. A token account reported by the node
+ // could belong to any holder of this mint, so it must never choose
+ // where the transfer goes.
+ final recipientTokenAccount = await _deriveAtaAddress(
+ ownerAddress: recipientAddress,
mint: tokenMint,
- rpcClient: rpcClient,
tokenProgramId: tokenProgramId,
);
- if (recipientTokenAccount.isEmpty) {
- throw Exception(
- "Cannot determine recipient token account for mint $tokenMint. "
- "Recipient may not have a token account for this mint. "
- "Please ensure the recipient has initialized an Associated Token Account (ATA) first.",
- );
- }
-
final senderTokenAccountKey = Ed25519HDPublicKey.fromBase58(
senderTokenAccount,
);
@@ -300,10 +294,9 @@ class SolanaTokenWallet extends Wallet {
"Token transaction missing a token program instruction.",
),
);
- final recipientTokenAccount = await _findOrDeriveRecipientTokenAccount(
- recipientAddress: txData.recipients!.first.address,
+ final recipientTokenAccount = await _deriveAtaAddress(
+ ownerAddress: txData.recipients!.first.address,
mint: tokenMint,
- rpcClient: rpcClient,
tokenProgramId: tokenProgramId,
);
@@ -353,7 +346,7 @@ class SolanaTokenWallet extends Wallet {
];
// Determine if this is a self-transfer.
- final isToSelf = senderTokenAccount == recipientTokenAccount;
+ final isToSelf = txData.recipients!.first.address == walletAddress;
// Create the temporary transaction record.
final tempTx = TransactionV2(
@@ -772,38 +765,6 @@ class SolanaTokenWallet extends Wallet {
}
}
- Future<String> _findOrDeriveRecipientTokenAccount({
- required String recipientAddress,
- required String mint,
- required RpcClient rpcClient,
- required String tokenProgramId,
- }) async {
- // First, try to find an existing token account
- final existingAccount = await _findTokenAccount(
- ownerAddress: recipientAddress,
- mint: mint,
- rpcClient: rpcClient,
- );
-
- if (existingAccount != null) {
- Logging.instance.i(
- "$runtimeType Found existing token account for recipient: $existingAccount",
- );
- return existingAccount;
- }
-
- // If no existing account found, try to derive the ATA
- Logging.instance.i(
- "$runtimeType No existing token account found, deriving ATA for recipient",
- );
-
- return await _deriveAtaAddress(
- ownerAddress: recipientAddress,
- mint: mint,
- tokenProgramId: tokenProgramId,
- );
- }
-
Future<String> _deriveAtaAddress({
required String ownerAddress,
required String mint,
### test/wallets/solana_token_account_creation_test.dart
@@ -78,6 +78,19 @@ void main() {
'rentEpoch': 0,
'data': ['', 'base64'],
};
+ // A hostile node reports another holder's account for the recipient.
+ final decoy = await Ed25519HDKeyPair.fromSeedWithHdPath(
+ seed: List.filled(32, 2),
+ hdPath: "m/44'/501'/0'/0'",
+ );
+ final expectedAddress = (await Ed25519HDPublicKey.findProgramAddress(
+ seeds: [
+ Ed25519HDPublicKey.fromBase58(SystemProgram.programId).bytes,
+ Ed25519HDPublicKey.fromBase58(program).bytes,
+ Ed25519HDPublicKey.fromBase58(Token2022Program.programId).bytes,
+ ],
+ programId: AssociatedTokenAccountProgram.id,
+ )).toBase58();
var mintLookupCount = 0;
var statusLookupCount = 0;
late final Isar isar;
@@ -149,18 +162,15 @@ void main() {
? <Map<String, Object>>[
{'pubkey': TokenProgram.programId, 'account': account},
]
- : scenario.recipientExists
- ? <Map<String, Object>>[
- {
- 'pubkey': AssociatedTokenAccountProgram.programId,
- 'account': account,
- },
- ]
- : <Map<String, Object>>[],
+ : <Map<String, Object>>[
+ {'pubkey': decoy.address, 'account': account},
+ ],
'getAccountInfo' =>
(params.first == TokenProgram.programId ||
params.first == Token2022Program.programId ||
- params.first == AssociatedTokenAccountProgram.programId)
+ params.first == decoy.address ||
+ (params.first == expectedAddress &&
+ scenario.recipientExists))
? account
: null,
'getLatestBlockhash' => {
@@ -254,27 +264,19 @@ void main() {
final result = await prepared;
expect(mintLookupCount, 0);
expect(result.solInstructions!.last.programId.toBase58(), program);
+ // The destination is the recipient's derived ATA whatever token
+ // account the node claims the recipient holds.
+ expect(
+ result.solInstructions!.last.accounts[2].pubKey.toBase58(),
+ expectedAddress,
+ reason: 'A node-reported account must never choose the destination',
+ );
if (scenario.recipientExists) {
expect(result.solInstructions, hasLength(1));
- expect(
- result.solInstructions!.last.accounts[2].pubKey.toBase58(),
- AssociatedTokenAccountProgram.programId,
- );
} else {
final creation = result.solInstructions!.first;
expect(creation.accounts[5].pubKey.toBase58(), program);
- final expectedAddress = await Ed25519HDPublicKey.findProgramAddress(
- seeds: [
- Ed25519HDPublicKey.fromBase58(SystemProgram.programId).bytes,
- Ed25519HDPublicKey.fromBase58(program).bytes,
- Ed25519HDPublicKey.fromBase58(Token2022Program.programId).bytes,
- ],
- programId: AssociatedTokenAccountProgram.id,
- );
- expect(
- creation.accounts[1].pubKey.toBase58(),
- expectedAddress.toBase58(),
- );
+ expect(creation.accounts[1].pubKey.toBase58(), expectedAddress);
}
// A trailing instruction must not change which program the pending
// record derives the recipient account from.Why this scored 78/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.