
| Audited | trustwallet/wallet-core at commit d40d24a63d92619167903369308bf0e2f7eb3a59 |
|---|---|
| Date | 11 October 2026 (audited again; first audit 11 October 2026) |
| How it ran | local run on our workstation, full audit, Standard review |
| Verdict after review | Pass with notes (Fail if a High finding remains after review, otherwise Pass with notes) |
Compared with the first audit
Same commit as the first audit: the project's default branch has no later commits (checked 11 October 2026), so nothing could have been fixed upstream in between. Each finding of the first audit (11 October 2026) was checked again against the code audited now. 53 findings in the first audit; 53 still open (36 found again, 17 not reported again but still present). This audit has 135 findings after review, 97 of them new.
| First audit | Finding | Reviewed rating then | Now | In this audit |
|---|---|---|---|---|
| #1 | ed25519 hand-ported signing | Low | Still open | #3 |
| #2 | Cardano extended-key TODO | Low | Still open | not reported again |
| #3 | secp256k1 ECDH hand-written | Low | Still open | not reported again |
| #4 | Polkadot zero-hash fallback | Low | Still open | not reported again |
| #5 | Polymesh zero-hash fallback | Low | Still open | not reported again |
| #6 | Pactus id hides encode errors | Low | Still open | not reported again |
| #7 | FFI sign returns empty sig on error | Low | Still open | not reported again |
| #8 | AES-CBC PKCS7 unpad unvalidated | Low | Still open | #1 |
| #9 | Keystore failures all "invalid password" | Low | Still open | not reported again |
| #10 | Missing PBKDF2 c defaults | Low | Still open | #4 |
| #11 | Jetifier still enabled | Low | Still open | not reported again |
| #12 | Android sample old Kotlin plugin | Low | Still open | #7 |
| #13 | Decrypt ignores stored dklen | Low | Still open | #92 |
| #14 | Unknown keystore type read as private key | Low | Still open | not reported again |
| #15 | C API decryptors skip key-kind check | Low | Still open | not reported again |
| #16 | Encoded export falls back to mnemonic | Low | Still open | not reported again |
| #17 | Private-key derivation accepts xpub | Low | Still open | not reported again |
| #18 | addAccount drops new details | Low | Still open | not reported again |
| #19 | Filled address applied to copy | Low | Still open | #22 |
| #20 | Account uniqueness not enforced on load | Low | Still open | #21 |
| #21 | CBOR decoder unbounded recursion | Low | Still open | #31 |
| #22 | CBOR quadratic validation / key rendering | Low | Still open | not reported again |
| #23 | CBOR count truncated in one walker | Low | Still open | #89 |
| #24 | ABI array decoder no budget | Medium | Still open | #24 |
| #25 | Pactus decoder allocates declared length | Medium | Still open | #26 |
| #26 | Base58 decode no length cap | Low | Still open | not reported again |
| #27 | Waves amounts as bare JSON numbers | Low | Still open | not reported again |
| #28 | lcov .deb via HTTP, installed as root | Medium | Still open | #45 |
| #29 | Build inputs no checksum | Low | Still open | #53 |
| #30 | CI sonar scanner no checksum | Low | Still open | #55 |
| #31 | emsdk moving branch, boost unverified | Low | Still open | #54 |
| #32 | CocoaPods spec no sha256 | Low | Still open | #58 |
| #33 | Dev containers unverified binaries | Low | Still open | #57 |
| #34 | Release scripts succeed after failed publish | Low | Still open | #50, #51 |
| #35 | Codegen create_dir before skip | Low | Still open | #47 |
| #36 | Scaffold re-run duplicates entries | Low | Still open | #127 |
| #37 | Mobile test skeleton overwrites files | Low | Still open | #46, #62 |
| #38 | Template writer truncates by default | Low | Still open | #63 |
| #39 | Dependency cache setup drifted | Low | Still open | #67 |
| #40 | Duplicated publish steps | Low | Still open | not reported again |
| #41 | NUL in ABI JSON aborts process | Low | Still open | #73 |
| #42 | AES-CBC encrypt, empty data + zero padding | Low | Still open | #78 |
| #43 | Keystore account parsing UB on absent keys | Medium | Still open | #77 |
| #44 | Keystore file overwritten in place | Low | Still open | #81, #94 |
| #45 | Android random source no error handling | Low | Still open | #91 |
| #46 | Wallet id unsanitised in file path | Low | Still open | #93 |
| #47 | Wallet delete ignores password | Info | Still open | #95 |
| #48 | Wallet-id index lost update | Low | Still open | #14 |
| #49 | scrypt p=0 / r=0 division by zero | Medium | Still open | #76 |
| #50 | Failed public derivation returns parent key | Low | Still open | #79 |
| #51 | BC sign-off gate passes on PR open | Low | Still open | #128 |
| #52 | BC sign-off accepted from any commenter | Low | Still open | #129 |
| #53 | new-blockchain script wrong path | Low | Still open | #133 |
Each finding keeps the number it has in the audit report. The rating shown first is the one after review; the first automated rating is listed with it. 95 findings were first rated Medium or High; 18 of them are Medium or High after review. Text marked "From the report" is quoted from the audit report; fixes are suggestions and were not tested. Code locations link to the file and line at the audited commit.
Medium after review (18)
swift/Sources/KeyStore.swift:61From the report
Evidence: self.watches.append(contentsOf: watches) then let data = try JSONEncoder().encode(watches)
the parameter shadows the property. Each call overwrites watches.json with only the new items, so earlier watches are lost at the next launch.
encode self.watches and write the file atomically.
swift/Sources/KeyStore.swift:347From the report
Evidence: importHDWalletWithEncryption(mnemonic: mnemonic, ..., coin: coins[0], ...) followed by getAccounts(password: newPassword, coins: coins)
the key is rebuilt from scratch and only default-derivation accounts are added back. Custom accounts and the key ID are lost silently.
re-encrypt the existing payload in place, or carry every account field and the ID over to the new key.
wasm/src/keystore/default-impl.ts:165From the report
Evidence: let privateKey = storedKey.privateKey(coin, Buffer.from(password));
an account added with a non-default derivation gets the default derivation's private key, which does not match its address.
add the derivation to the account type and pass it when deriving the key.
rust/tw_evm/src/abi/decode.rs:199From the report
Evidence: let tail = &data[tail_offset..]; ... for elem_idx in 0..len { let res = decode_param(kind, tail, new_offset)
array elements may all point at the same inner data. Calldata of about 1 MB for bytes[] or nested arrays can then expand to gigabytes, and the expansion grows exponentially with nesting. Contract-call decoding takes calldata supplied by a website, so a malicious site can crash the wallet.
decode against a total budget for elements and bytes, tied to the input length. Reject offsets that point backwards or overlap.
From the report
Evidence: let field_value = &data[&field.name]; ... let mut encoded = encode_data(custom_types, field_property, field_value)?;
a missing field reads as JSON null, so a type that refers to itself recurses without end. The stack overflows and the app aborts. The input is typed data supplied by a website through the sign-typed-data request.
carry a depth counter (limit about 32), require object values, fail on missing fields and reject cyclic type graphs.
From the report
Evidence: let len = *VarInt::decode(r)?; let mut buf = vec![0; len as usize];
about ten bytes of input can request an allocation of up to 2^64 bytes. That aborts the process, for example through the transaction-hash utility.
limit the length by the bytes remaining, or read through a bounded reader.
src/Cbor.cpp:408From the report
Evidence: if (!nextElem.isValid()) { return false; } (recursive validity, length and dump walks)
deeply nested arrays or tags in WebAuthn or Cardano input cause unbounded recursion. A stack overflow is not caught by the surrounding try/catch.
add a depth counter (32 to 64) to every recursive walk and fail when it is exceeded.
tools/install-sys-dependencies-linux:17From the report
Evidence: wget -O "$LCOV_DEB" http://mirrors.kernel.org/ubuntu/pool/universe/l/lcov/lcov_1.15-1_all.deb then sudo apt-get install "$LCOV_DEB"
a network attacker can replace the package and run code as root on any developer machine or CI runner that bootstraps the build.
download over HTTPS and verify a pinned SHA-256 before installing.
src/Stellar/Signer.cpp:230From the report
Evidence: if (asset.issuer().length() > 0 && Address::isValid(asset.issuer()) && asset.alphanum4().length() > 0) { assetType = 1; (otherwise native)
if the issuer is invalid or the code is empty, the payment silently becomes a native XLM payment of the same amount. That is a different and possibly far more valuable transfer than the one requested. Codes longer than four characters are also truncated.
if any asset field is set but invalid, return an invalid-parameters error. Reject codes that are too long.
src/Keystore/ScryptParameters.cpp:87From the report
Evidence: if ((r > std::numeric_limits<uint32_t>::max() / 128 / p) ||
a crafted key file reaches this check on import or load. Integer division by zero is undefined behaviour and traps on x86.
reject p = 0 and r = 0 before dividing.
src/Keystore/Account.cpp:31From the report
Evidence: if (json[CodingKeys::derivationPath].is_object()) { ... coin = TWCoinType(uint32_t(derivationPath.indices[1].value));
a crafted account entry triggers undefined behaviour or an out-of-bounds read on import.
check that each key is present and that there are at least two path indices, and throw otherwise.
src/HDWallet.cpp:54From the report
Evidence: mnemonic_to_seed(mnemonic.c_str(), passphrase.c_str(), seed.data(), nullptr);
non-ASCII passphrases derive different seeds than other BIP-39 wallets, so a restore can appear to lose funds. Passphrases longer than 256 bytes are truncated, so different long passphrases can produce the same seed.
normalise both to NFKD and reject passphrases longer than 256 bytes.
jni/cpp/TWJNIString.cpp:16From the report
Evidence: const auto *chars = env->GetStringUTFChars(string, nullptr);
an emoji in a passphrase produces a different seed on Android than on iOS or WASM.
convert from UTF-16 to standard UTF-8 and check for null.
From the report
Evidence: let parts = string.split(separator: "_") ... parts[0].hasPrefix(prefix),
the input "_" crashes any caller, including Codable decoding of remote JSON.
guard let first = parts.first, parts.count <= 2.
From the report
Evidence: (self.message_header_mut().num_required_signatures - self.message_header_mut().num_readonly_signed_accounts) as usize - 1
an inconsistent header wraps around, and the later insert panics, which aborts the process.
validate the header on decode and use checked arithmetic.
From the report
Evidence: let internal_key = XOnlyPublicKey::from_slice(xonly.as_slice()).unwrap();
any valid v1 address whose program is not on the curve panics during signing.
build OP_1 <32 bytes> directly, or return an error.
src/Cardano/Signer.cpp:349From the report
Evidence: [key]([[maybe_unused]] auto&& sum, auto&& si) { return si.tokenBundle.getAmount(key); } and selectedAmount += i.amount;
a token spread over several UTXOs causes a spurious low-balance error or too few inputs being selected.
accumulate sum + token amount, and add token amounts in the loop.
src/EOS/Name.cpp:35From the report
Evidence: if (c >= '1' && c <= '5') return c - '1' + 1; return 0;
a recipient such as alice6 or Bob is serialised as a different account, possibly one that exists.
throw on characters outside [a-z1-5.].
Low after review (110)
src/Encrypt.cpp:82From the report
Evidence: const byte paddingSize = result[result.size() - 1]; if (paddingSize <= result.size()) {
the code never checks that the padding byte is between 1 and 16, or that the padding bytes all match. A wrong key or corrupt ciphertext is returned as successfully decrypted garbage instead of an error.
require 1 ≤ padding ≤ 16 and check that every padding byte equals it, in constant time, or else throw. Prefer an authenticated mode (AES-GCM, or encrypt-then-MAC).
rust/tw_evm/src/modules/signer.rs:32From the report
Evidence: let chain_id = U256::from_big_endian_slice(&input.chain_id)
an absent chain ID is not treated as an error. A legacy transaction is then signed without replay protection and can be replayed on other EVM chains.
reject an empty or zero chain ID for legacy and enveloped transactions. Apply the same check in the compiler path.
rust/tw_keypair/src/ed25519/secret.rs:98From the report
Evidence: let r = Scalar::from_hash(h); ... let s = k * self.key + r;
custom signature code has to reproduce every check of a maintained implementation, and an earlier advisory about this routine is cited in its own comments.
use a maintained Ed25519 API for the standard variants. Confine the custom routine to the non-standard variants and cover it with test vectors and fuzzing.
src/Keystore/PBKDF2Parameters.cpp:38From the report
Evidence: if (json.count(CodingKeys::iterations) != 0) { iterations = json[...]; }
a required key-derivation parameter that is missing is replaced by a default instead of being reported.
treat a missing iteration count as an import error.
From the report
Evidence: .with_gas_unit_price(input.gas_unit_price).with_max_gas_amount(input.max_gas_amount)
fields left unset arrive as 0 and replace the built-in defaults. The chain ID is also truncated with as u8.
apply these values only when they are non-zero, and reject chain IDs above 255.
samples/android/build.gradle:14From the report
Evidence: ext.kotlin_version = '1.3.50' with com.android.tools.build:gradle:7.2.1 and JavaVersion.VERSION_17
Kotlin 1.3.50 predates Gradle 7 and JDK 17. The sample will most likely fail to build, with errors that look like project problems. It also uses the removed kotlin-android-extensions.
raise the Kotlin plugin to a release that supports this Gradle and JDK, and replace synthetic view access with view binding.
swift/Sources/KeyStore.swift:349From the report
Evidence: } else if let key = StoredKey.importPrivateKeyWithEncryption(privateKey: privateKeyData, ...)
the encoded-key form is not re-imported, so hasPrivateKeyEncoded turns false after the update.
when the wallet has an encoded key, re-import it through the encoded import path.
swift/Sources/KeyStore.swift:88From the report
Evidence: wallets.append(wallet) then try save(wallet: wallet)
if the save fails, the caller gets an error but an unsaved wallet stays in the list.
save first, then append. Alternatively, remove the entry when the save fails.
swift/Sources/KeyStore.swift:43From the report
Evidence: for url in accountURLs { if url.lastPathComponent == KeyStore.watchesFileName { continue } guard let key = StoredKey.load(path: url.path)
a crash between the temp-file write and the rename leaves a temp file. On the next launch it loads as a duplicate wallet with the same key ID.
load only files with the key-file naming pattern, skip .tmp files, deduplicate by ID and clean up stale temp files.
From the report
Evidence: return this.storage.set({ [id]: wallet, [this.walletIdsKey]: ids,
wallet records share a namespace with the ID index and with anything else in the extension's storage. An imported wallet whose ID collides with another key overwrites that key.
put every wallet key under an owner prefix, validate the ID format, and store and check a record kind.
From the report
Evidence: return this.getWalletIds().then((ids) => { if (ids.indexOf(id) === -1) { ids.push(id); }
two concurrent saves or deletes read the same list, and the later write drops the other wallet's ID. That wallet then disappears from loadAll(). In addition, delete() returns early for a wallet missing from the index and leaves its data behind.
serialise index changes through one promise queue, and always remove the record on delete.
wasm/src/keystore/default-impl.ts:146From the report
Evidence: let hdWallet = storedKey.wallet(Buffer.from(password)); ... storedKey.delete(); hdWallet.delete();
a wrong password or other error skips the cleanup. Each failed call leaks WASM heap, including HD wallet objects that hold seed material.
release native objects in try/finally in every keystore method.
swift/Sources/KeyStore.swift:23From the report
Evidence: public var watches = [Watch]()
callers can change the list without it being saved.
make it public private(set).
swift/Sources/KeyStore.swift:379From the report
Evidence: wallets.removeAll(keepingCapacity: false) ... try? fileManager.removeItem(at: url)
watches stay in memory after destroy(). Deletion errors are swallowed, and delete() removes the wallet from the list before removing its file.
clear watches, surface deletion errors, and delete the file before the list entry.
src/Keystore/StoredKey.cpp:314From the report
Evidence: if (!account.address.empty() && !account.publicKey.empty() && TW::validateAddress(account.coin, account.address)) { continue;
the skip test checks only the address format. It does not check that the address matches the public key and derivation, so a mismatched address is never repaired.
skip only when re-deriving from the public key gives the stored address.
src/Keystore/StoredKey.cpp:202From the report
Evidence: account.address = TW::deriveAddress(account.coin, pubKey, account.derivation);
the key comes from the derivation path, while the address format comes from the derivation enum. No write site checks that these agree.
state the invariant, assert it on add, load and update, and add a verify step.
src/Keystore/StoredKey.cpp:460From the report
Evidence: for (auto& accountJSON : json[CodingKeys::SK::activeAccounts]) { accounts.emplace_back(accountJSON);
duplicate accounts in an imported file are kept and saved again.
clear the list before loading and apply the unique-address check.
src/Keystore/StoredKey.cpp:210From the report
Evidence: Account accountLval = account.value(); return fillAddressIfMissing(accountLval, wallet);
callers that read the stored list see an empty address, while callers of account() see a filled one.
write the derived values back into the stored entry.
From the report
Evidence: /// TODO generate like CoinType.
each new derivation must be patched into several copies. An unknown name in the registry is silently read as the default derivation.
generate the enum from the registry, and make unknown names a parse error.
From the report
Evidence: let mut verify_order = true; while verify_order { verify_order = false;
a crafted bag of 4,096 cells forces about n passes of O(n) lookups, which is seconds of CPU time on a phone.
use one linear topological sort.
src/Everscale/CommonTON/Cell.cpp:325From the report
Evidence: if (index > cellCount || index <= i) { (only forward references required); recursive fillContext(*ref, ctx);
a long linear chain of cells in the account-state data overflows the stack, both while serialising and while freeing the cells.
cap the cell count and depth (1,024), and make the serialiser and destructor iterative.
src/Tron/Signer.cpp:569From the report
Evidence: auto parsed = nlohmann::json::parse(rawJson); ... output.set_json(parsed.dump());
the only limit is a 1 MB byte cap. A deeply nested document passes through a recursive parser and serialiser.
parse with a depth limit, or build the output from the validated fields only.
src/Hedera/Address.cpp:62From the report
Evidence: if (std::regex_match(string, match, gEntityIDRegex)) {
the standard library's regex engine is recursive on some platforms. A long run of digits can exhaust the stack during address validation.
reject strings longer than about 64 characters before matching, or parse the three parts by hand.
src/Keystore/PBKDF2Parameters.cpp:42From the report
Evidence: iterations = json[CodingKeys::iterations];
a crafted key file can set PBKDF2 iterations to 0 or 4 billion, or scrypt costs that need gigabytes of memory. Decryption then hangs or runs out of memory, or a trivially weak setting goes unflagged.
validate minimum and maximum iterations, key length and salt for PBKDF2, and practical bounds for scrypt's n, r and p.
From the report
Evidence: let mut res = vec![0_u8; byte_count];
an oversized count would abort on allocation instead of returning an error. Current callers pass a constant size.
check byte_count * 8 against the remaining bits with checked arithmetic before allocating.
From the report
Evidence: .map(|j| Argument::NestedResult(split_primary, j as u16))
with 65,536 or more recipients, indices wrap and amounts are routed to earlier recipients.
use u16::try_from and reject counts that are too large.
From the report
Evidence: // TODO: Check crc32 ... let ref_num = d1 & 0b111;
up to 7 references per cell are accepted where 4 is the limit, and the size fields and checksum are not checked.
enforce the protocol limits and verify the CRC when it is present.
rust/tw_encoding/src/base32.rs:18 (line corrected on review; the report cites :44)From the report
Evidence: static ENCODINGS: RefCell<EncodingMap> = RefCell::new(HashMap::new());
every distinct alphabet string passed by a caller is cached permanently.
cap the cache, or cache only the default alphabets.
From the report
Evidence: const MAX_RECURSION_DEPTH: usize = 20;
the recursive protobuf message is fully decoded, recursively, before the depth check runs.
limit input size or depth at decode time, and keep the later check as a second layer.
From the report
Evidence: #[derive(PartialEq, Eq, Clone, Hash)] pub struct Cell { ... references: Vec<CellArc>,
on a graph where references are shared, printing or deriving a hash visits 2^depth nodes.
compare and hash by the cell hash, and print a bounded summary.
src/Everscale/CommonTON/Cell.cpp:151From the report
Evidence: intermediate.reserve(cellCount);
the reservation is sized from a 32-bit count in the header, not from the bytes actually present.
reject counts larger than the remaining bytes allow, and bounds-check the skip at line 140.
src/Everscale/CommonTON/Cell.cpp:356From the report
Evidence: depth = std::max(depth, static_cast<uint16_t>(ref->depth + 1));
very deep input produces a wrong hash with no error.
reject depths above 1,024.
src/Bitcoin/Transaction.cpp:29From the report
Evidence: auto hashPrevouts = getPrevoutHash(); (inside the per-input pre-image)
hashes shared by all inputs are recomputed for every input. A plan supplied by the caller has no input cap.
compute the shared hashes once per transaction and cap the input count in the signer.
codegen/lib/coin_skeleton_gen.rb:42From the report
Evidence: path = File.join(folder, fileName) File.write(path, result)
running the documented example against an existing coin replaces its sources, proto and tests with templates. They can only be recovered from version control.
skip or abort when the target exists, as the newer generator does.
From the report
Evidence: fs::create_dir(coin_tests_dir)?; if tw_coin_type_tests_path.exists() {
the skip branch can never be reached. The run fails after earlier files have already been edited.
use create_dir_all and run all checks before making any edits.
codegen-v2/src/codegen/cpp/mod.rs:42From the report
Evidence: integration_tests_directory().join("chains").join(coin.coin_type())
the newer generator ignores the registry's test-folder name, so the same coin gets tests in two places.
honour testFolderName, and ideally retire one of the generators.
cmake/Protobuf.cmake:5From the report
Evidence: protobuf-3.20.3 (also in the podspec, xcconfig and dependency list); swift-protobuf is 1.18.0 in one file and 1.29.0 in another
the generator and the linked runtime must match, and the copies already disagree.
make one file the single source and pass the version through to the build files.
tools/android-release:29From the report
Evidence: ./gradlew publishAllPublicationsToGitHubPackagesRepository ... || echo "Warning: GitHub Packages publishing failed"
a failed release prints "Android build uploaded".
fail on a publish error and verify the published artifact.
tools/kotlin-release:25From the report
Evidence: ... publishAllPublicationsToGitHubPackagesRepository -Pversion="$version" || echo "Warning: ..."
same as finding 50 for the Kotlin package.
same as finding 50.
tools/download-dependencies:51From the report
Evidence: curl -fSsOL https://github.com/protocolbuffers/protobuf/releases/download/... tar xzf ...
record a SHA-256 for each archive and check it before extracting.
tools/install-wasm-dependencies:7From the report
Evidence: git clone https://github.com/emscripten-core/emsdk.git
pin a tag or commit, and verify the boost archive.
tools/sonarcloud-analysis:8From the report
Evidence: curl -sSfL ".../sonar-scanner-cli/${TARGET}" --output "${TARGET}"
pin and verify the scanner's SHA-256.
From the report
Evidence: curl -O -L ... "https://golang.org/dl/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
use a SHA-pinned setup action or verify the published checksum. Go 1.19 is also end of life.
.devcontainer/Dockerfile:58From the report
Evidence: curl -sSL ... swift-5.8-RELEASE-ubuntu22.04.tar.gz -o swift-5.8.tar.gz
verify a checksum or signature, as the same file already does for rustup.
tools/ios-release:58From the report
Evidence: s.source = { http: '${download_url}' }
add sha256: to the source, as the Swift package path already does.
.github/workflows/docker.yml:19From the report
Evidence: curl -L ... hadolint-Linux-x86_64 -o hadolint && chmod +x hadolint
verify the checksum or use a SHA-pinned action, and add a permissions: block.
tools/install-android-dependencies:34From the report
Evidence: curl -fSsOL $DOKKA_CLI_JAR
pin a SHA-256 for each jar.
tools/library:27From the report
Evidence: gh release upload $tag $filename --clobber
refuse to overwrite unless replacement is requested explicitly.
codegen/lib/coin_skeleton_gen.rb:102From the report
Evidence: coin_test_gen.generate_coin_test_file(coin, 'TWCoinTypeTests.cpp.erb', true)
pass false so an existing, possibly hand-edited file is kept.
From the report
Evidence: let file_to_write = fs::File::create(write_to_path)?;
open the file with create_new(true).
.github/workflows/linux-ci.yml:45 (line corrected on review; the report cites :43)From the report
Evidence: tools/generate-files native
run git diff --exit-code after generation.
.github/workflows/android-ci.yml:6From the report
Evidence: paths-ignore: (repeated in the iOS, Kotlin, Kotlin-sample and Rust workflows)
generate the list from one source.
.github/workflows/linux-ci.yml:23From the report
Evidence: - name: Cache internal dependencies ... uses: actions/cache@...
extract a composite action with one key formula.
Dockerfile:61From the report
Evidence: RUN rustup default nightly-2025-12-11 RUN cargo install --force cbindgen --locked
have both Dockerfiles call the shared install script.
From the report
Evidence: uses: actions/checkout@v4 ... uses: actions/github-script@v7
pin by commit SHA, as the other workflows do.
rust/tw_keypair/src/tw/private.rs:89From the report
Evidence: ed25519::cardano::ExtendedPrivateKey::try_from(&bytes[Self::EXTENDED_CARDANO_RANGE])
a 32-byte key passes the general length test, then is sliced to 192 bytes and panics. The build aborts on panic, so the exported validity function kills the host.
check the exact length for the selected curve before slicing.
rust/tw_hash/src/ffi.rs:40 (also rust/tw_encoding/src/ffi.rs:72, 123, 156, 214)From the report
Evidence: let input = std::slice::from_raw_parts(input, input_len);
the C++ wrappers pass vector.data(), which may be null for empty data. Building a slice from a null pointer is undefined behaviour even when the length is 0.
use the existing helper that maps (null, 0) to an empty slice.
rust/tw_memory/src/ffi/tw_string.rs:55From the report
Evidence: TWString(CString::new(s).expect("CString::new(String) should never fail"))
a function name containing \u0000 in ABI JSON supplied by a caller reaches this conversion. The panic aborts the app.
make the conversion fallible and return null at the boundary.
From the report
Evidence: pub struct PrivateKey { secret: FieldElement, } (no zeroizing on drop)
every other key type wipes its secret, so this one leaves key material in freed memory.
implement zeroize-on-drop.
From the report
Evidence: let bytes = hex::decode(s).map_err(|_| KeyPairError::InvalidPublicKey)?;
the secret bytes stay in freed memory, and the error variant names the wrong key type.
wrap the decoded bytes in Zeroizing and return InvalidSecretKey.
src/Encrypt.cpp:42From the report
Evidence: for (idx = 0; idx < resultSize - blockSize; idx += blockSize) {
with an empty input resultSize is 0, so the bound wraps around. The loop then reads and writes through empty buffers, which can crash or corrupt the heap.
handle inputs shorter than one block before the loop.
src/HDWallet.cpp:149From the report
Evidence: hdnode_private_ckd(&node, index.derivationIndex());
a step that is not allowed on the curve (non-hardened ed25519) fails silently, and the parent key is returned as the child.
check each result and throw on failure. The same applies to lines 256, 271 and 288 to 323.
src/Keystore/StoredKey.cpp:512From the report
Evidence: auto stream = std::ofstream(path);
the public store function truncates the only copy of the encrypted seed before writing it again.
always write a temporary file, then flush and rename. Remove or deprecate the in-place variant.
src/PrivateKey.cpp:274From the report
Evidence: ecdsa_sign_digest_checked(&secp256k1, key().data(), ...
each sign or derive call leaves a heap copy of the key in memory.
point into the stored bytes, or use a wiping container.
Review: ` returns a copy)
src/HDWallet.cpp:195From the report
Evidence: const auto node2 = getNode(*this, curve, stakingPath); auto pkData2 = Data(node2.private_key, ...
the second node, the copied key buffers and the raw entropy are never wiped.
wipe every local that holds key material, or use wiping types.
src/interface/TWStoredKey.cpp:268From the report
Evidence: const auto data = key->impl.payload.decrypt(passwordData); const auto string = std::string(data.begin(), data.end());
plaintext secrets stay in freed memory, including on early error paths.
wipe the intermediates on every path, as the core already does.
src/interface/TWHash.cpp:89From the report
Evidence: tc_blake2b_Personal(dataBytes, ..., resultBytes.data(), outlen);
an invalid output length or personalisation is returned as a valid all-zero hash.
check the return value and return null on failure.
src/Bech32Address.cpp:19From the report
Evidence: std::get<0>(dec).compare(0, hrp.length(), hrp) != 0
an expected prefix of cosmos accepts cosmosvaloper1…, and bc accepts bcrt1…. Bech32m strings are also accepted where Bech32 is required.
compare the prefix for equality and enforce the checksum variant.
src/interface/TWPublicKey.cpp:46From the report
Evidence: return new TWPublicKey{ pk->impl.extended() };
an off-curve compressed key passes validation. Its later conversion throws through an extern "C" function and aborts the host.
decode the point during validation, and catch exceptions in the C API.
src/interface/TWPrivateKey.cpp:97From the report
Evidence: auto result = pk->impl.sign(d, curve);
a curve mismatch throws, and the process terminates.
wrap these functions in try/catch and return null.
src/Cbor.cpp:299From the report
Evidence: uint32_t count = ... (uint32_t)(typeDesc.value * countMultiplier);
other code uses the full 64-bit count, so different parts of the parser can read the same hostile input differently.
use 64-bit counts, reject overflow, and reject counts larger than the remaining bytes.
jni/cpp/Random.cpp:66From the report
Evidence: env->CallVoidMethod(random, nextBytes, array); jbyte* bytes = env->GetByteArrayElements(array, nullptr); memcpy(buf, bytes, len);
a failed JNI call leaves zeros that are then used as entropy for keys, IVs or salts.
check every JNI call and pending exception, and terminate on failure, as the /dev/urandom path does.
From the report
Evidence: auto derivedKey = Data(scryptParams.desiredKeyLength); (decryption uses the fixed default)
re-encrypting with an imported key length that is too short reads out of bounds, and a length that is too long makes the key unrecoverable.
validate the key length and use the same value in both directions.
wasm/src/keystore/fs-storage.ts:17From the report
Evidence: return this.directory + id + ".json";
an ID taken from an imported wallet object can write, read or delete .json files outside the keystore directory.
accept only strict ID patterns, and check that the resolved path stays inside the directory.
wasm/src/keystore/fs-storage.ts:27From the report
Evidence: return fs.writeFile(this.getFilename(id), JSON.stringify(wallet));
a crash can truncate the only copy of the encrypted key, and the file is created with default permissions.
write a temporary file with mode 0600, then flush and rename.
swift/Sources/AnySigner.swift:58From the report
Evidence: let jsonString = TWStringCreateWithNSString(json) ... defer { TWDataDelete(keyData) }
add TWStringDelete(jsonString) to the defer block.
swift/Sources/KeyStore.swift:109From the report
Evidence: guard let index = wallets.firstIndex(of: wallet) else { fatalError("Missing wallet") }
a stale wallet object kills the host app.
throw an error instead. The same applies at lines 331 and 363.
From the report
Evidence: actual fun signJson(...): String = TODO()
implement it, or throw a documented unsupported-operation error.
flutter/lib/wallet_core.dart:8From the report
Evidence: path.join(Directory.current.path, 'lib', 'libTrustWalletCore.so',
whoever controls the working directory can plant a library.
resolve the library from the package or executable location.
From the report
Evidence: let mut builder = self.builder_with_token_transfer_to_fee_payer_if_applicable()?; builder.maybe_advance_nonce(...)
the nonce-advance instruction must come first. Otherwise the transaction is not treated as a durable-nonce transaction and is rejected or expires.
add the nonce instruction first, in every builder that uses the sponsored fee transfer.
rust/tw_evm/src/address.rs:166From the report
Evidence: let addr_hash = H160::from_str(addr_hex)...
a mistyped recipient is accepted without detection.
verify the EIP-55 checksum when the address mixes upper and lower case.
rust/tw_evm/src/message/signature.rs:45From the report
Evidence: v: v.low_u8(),
chain IDs above about 110 produce signatures that verifiers cannot recover.
return an error when v does not fit in one byte.
rust/tw_evm/src/message/eip191.rs:37From the report
Evidence: match hex::decode(&self.user_message) { Ok(raw_msg) => do_extend(&raw_msg),
text such as deadbeef is signed as bytes, so the user signs something other than what is displayed.
decode as bytes only with an explicit 0x prefix, or add an explicit flag.
From the report
Evidence: let ticker = Brc20Ticker::new(ticker).unwrap();
propagate the error with ?.
From the report
Evidence: if let Some(ref witness_utxo) = self.utxo_psbt.witness_utxo { self.build_witness_utxo(witness_utxo)
a PSBT supplied by a third party can misstate input amounts and hide an inflated fee.
prefer or cross-check the full previous transaction, and bound the fee before signing.
samples/kmp/shared/build.gradle.kts:53From the report
Evidence: implementation("com.trustwallet:wallet-core-kotlin:+")
pin an exact version.
swift/Sources/KeyStore.swift:38From the report
Evidence: let data = try Data(contentsOf: watchesFile) watches = try JSONDecoder().decode([Watch].self, from: data)
the error is thrown before any wallet is loaded, so init fails as a whole.
load watches with a fallback, and write the file atomically.
From the report
Evidence: default: return defaultsForMissing; (blockchain Bitcoin)
accounts for a coin this build does not know can have their saved addresses overwritten with Bitcoin-derived ones. The Rust registry returns an error for the same case.
return an explicit unsupported result, and refuse such coins in dispatch.
From the report
Evidence: -(reversed_exponent as i32)
1e4294967296 truncates to exponent 0, passes validation, and is signed as an amount of 1.
use i32::try_from and reject out-of-range values.
src/Bitcoin/Script.cpp:68From the report
Evidence: std::copy(std::begin(bytes) + 1, std::begin(bytes) + 1 + PublicKey::secp256k1Size, (in the 65-byte branch)
uncompressed P2PK outputs cannot be signed, because the wrong key is looked up.
copy 65 bytes in that branch.
src/NEAR/Address.cpp:35From the report
Evidence: return Data(decoded.begin(), decoded.end() - legacyChecksumSize);
recompute the checksum and compare it.
src/NEAR/Address.cpp:56From the report
Evidence: auto data = publicKey.compressed().bytes; std::copy(std::begin(data), std::end(data), std::begin(bytes));
a 33-byte or larger key passed through the C API writes past the array.
require an ed25519 key of 32 bytes, and validate the key type against the coin during dispatch.
src/IOST/Account.cpp:41From the report
Evidence: activeKey = Data(activeKeyBytesPtr, activeKeyBytesPtr + PrivateKey::_size);
require exactly 32 bytes (the same applies to the owner key).
src/Filecoin/Address.cpp:57From the report
Evidence: auto k = byte & SCHAR_MAX; actorID |= k << (remainingPos * 7);
large IDs decode to a different actor.
use uint64_t and reject encodings that are too long.
src/CoinEntry.h:81From the report
Evidence: input.ParseFromArray(dataIn.data(), (int)dataIn.size());
partially parsed input is signed.
return an input-parse error when parsing fails, as the compiler template already does.
src/rust/RustCoinEntry.h:45From the report
Evidence: google::protobuf::util::JsonStringToMessage(json, &input);
malformed JSON is signed as a partly empty input. The same pattern appears in seven coins.
check the returned status.
src/interface/TWAnySigner.cpp:21From the report
Evidence: auto result = TW::anySignJSON(coin, jsonString, keyData);
an exception from a coin's JSON signer terminates the app.
wrap the call in try/catch and return an empty string.
src/interface/TWEthereumAbiValue.cpp:49From the report
Evidence: EthAbi::ValueEncoder::encodeAddress(*reinterpret_cast<const Data*>(value), data);
validate the size first, or catch the exception.
src/Bitcoin/Script.cpp:251From the report
Evidence: assert(hash.size() == 20);
release builds produce malformed or unspendable scripts without any error.
return an empty script, or throw and catch at the C layer.
src/Zilliqa/Signer.cpp:93From the report
Evidence: const auto preImage = Signer::getPreImage(input, address); const auto signature = key.signZilliqa(preImage);
return an invalid-address error when the preimage is empty.
src/Nano/Signer.cpp:132From the report
Evidence: try { ... output = signer.build(); } catch (...) {} return output;
set an error code and message in the catch block.
From the report
Evidence: enum_region.push_line_before(format!(" TWCoinType{coin_type} = {coin_id_number},"));
a second run duplicates enum values and dispatcher cases, and the build fails.
check whether the line is already present before inserting it.
From the report
Evidence: if (!hasReminder) { core.info('No BC-risk reminder posted; nothing to verify.'); return;
the verify job does not wait for the job that posts the reminder. Fork PRs cannot post it at all, so the gate passes without engaging on the keystore, proto and registry paths it is meant to guard.
add needs: on the posting job, or compute the guarded-file list inside the verify job.
From the report
Evidence: const signoff = comments.find(c => { const tokenMatch = c.body.match(tokenRegex);
any GitHub account can post the sign-off token. The docs/bc-footguns.md file that contributors are told to read does not exist in this tree.
require an owner, member or collaborator who is not the PR author.
tools/rust-bindgen:60From the report
Evidence: cargo build ... --target aarch64-apple-ios ... --release --lib & wait
a bare wait returns 0, so lipo packages whatever stale library is left over.
wait on the job's PID and check its status.
.github/workflows/rust.yml:221From the report
Evidence: if ! grep -qE '^[ \t]*[profile.dev]' Cargo.toml; then
the pattern matches unrelated lines, so the intended profile change never happens.
use grep -qF '[profile.dev]'.
tools/lint-all:8From the report
Evidence: find src ... -not -path "./src/proto/*" ... -exec clang-tidy -quiet -p=build '{}' \;
the exclusion path never matches find's output form, and -exec … \; discards the tool's exit status. The same applies to tools/lint-cppcheck-all.
write the path as src/proto/* and use -exec … +.
tools/new-blockchain:10From the report
Evidence: pushd codegen codegen/bin/newcoin-mobile-tests $1
run the command from the repository root, and add set -e.
tools/gh-download-workflow-artifact:11From the report
Evidence: ARTIFACT_ID=$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts" --jq ...
the size comparison silently reports "no change" when no baseline is found.
paginate or filter by name, and fail or report explicitly when no baseline exists.
Dockerfile:68From the report
Evidence: COPY . /wallet-core (.dockerignore lists only .gitignore)
local build outputs and any local configuration are baked into the image, and stale inputs can skip the clean downloads.
exclude .git, build/, rust/target/, wasm-build/ and local environment files.
Info after review (7)
From the report
Evidence: TokenInstructionBuilder::transfer_checked(sender_token_address, token_mint_address, recipient_token_address, ...)
the caller-supplied token accounts are not checked against the associated token account derived from owner, mint and program. A swap between the classic token program and Token-2022 is only caught on chain.
derive the associated token account and compare it with the supplied one before signing.
From the report
Evidence: an 825-line builder covering send, IBC, staking, wasm, terra, thorchain, stride, auth and gov
unrelated chain logic in one file makes changes and reviews riskier.
split the chain-specific builders into separate modules.
src/Bitcoin/InputSelector.cpp:122From the report
Evidence: auto slices = slice(sorted, static_cast<size_t>(numInputs)); Note: keep the count cap at every entry point, or use the single-pass selector for large sets.
src/Cardano/Signer.cpp:22 (line corrected on review; the report cites :25)From the report
Evidence: static const auto PlaceholderFee = 170000; static const auto ExtraInputAmount = 500000; Note: if fee parameters should follow protocol updates, accept them through the signing input.
Package.swift:20From the report
Evidence: .../4.2.9/SwiftProtobuf.xcframework.zip, while the release script uploads WalletCoreSwiftProtobuf.xcframework.zip
the released Swift package composition is never built or resolved in CI, and the manifest has already drifted from the release script.
generate Package.swift from the release script, and add a CI job that resolves it in a consumer project.
From the report
Evidence: let mut file = std::fs::File::create(&file_path)?;
refuse to overwrite files that lack a generated-file marker.
wasm/src/keystore/default-impl.ts:32From the report
Evidence: delete(id: string, password: string): Promise<void> { return this.storage.delete(id, password);
neither storage backend checks the password, so wallets can be deleted without authentication.
verify the password before deleting, or remove the parameter.