Encrypted store-key addresses changed from `SHA256(key)[..12]` to a tagged hash, so entries written by earlier revisions become silently unreachable

Open
#193 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
56/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust
Domain
database

Research direction

Start with lwk_common/src/store.rs at EncryptedStore::effective_key and lwk_common/src/encrypt.rs at the deterministic nonce derivation; compare these with the previous lwk_boltz/src/store.rs implementation described in the issue. Then inspect lwk_boltz/src/store.rs read helpers and reproduce the legacy-key lookup using the supplied test recipe. Done means earlier entries remain readable or the read path detects and reports the legacy lookup miss.

Written by the indexing model from the issue text.

Description

Summary

Boltz swap persistence encrypts store keys, not just values, and uses the ciphertext as the entry's key
in the underlying store, so the nonce fixes the on-disk address of every entry. Commit f771d1dc
("common: add crypto module and refactor encryption") replaced the plain SHA256-derived nonce with a
domain-separated tagged hash; because the address is the ciphertext, every plaintext key now maps to a
different store key, and no code path derives the old address. The break is silent: EncryptedStore::get
(effective_key, lwk_common/src/store.rs:479) returns Ok(None) on a lookup miss, and
store_keys::get_pending_swaps (lwk_boltz/src/store.rs:143) collapses that into an empty list. Swap data
persisted by an earlier revision becomes invisible after an upgrade.

Environment

  • Repository: Blockstream/lwk
  • Current default branch: commit f2c64c74d5f9ef1079e842798a323d82e7dfaa89
  • Reproduced at f771d1dc863d7db7221088426d50613c9e3828f0 (the commit that introduced the tagged-hash
    nonce, whose parent is a87d89122a0631715602908d5be7ed9643f530a6); still present in the current code at
    f2c64c74d5f9ef1079e842798a323d82e7dfaa89.
  • Toolchain used for the reproduction: Rust 1.85.1, offline.
  • Current key-encryption entry point: lwk_common/src/store.rs:479
    (EncryptedStore::effective_key); nonce derivation: lwk_common/src/encrypt.rs:119 and
    lwk_common/src/encrypt.rs:120-122; nonce tag: lwk_common/src/encrypt.rs:15. The Boltz store now
    delegates to EncryptedStore and no longer contains its own encrypt_key.

The parameter type changed from &str (key.as_bytes()) to AsRef<[u8]> (key.as_ref()), but the
derivation is otherwise identical, and it still decides the address of every store key.

The reproduction used the fixed cipher key [42u8; 32].

Expected behavior

Store keys should address the same entry across the change, or a lookup that fails because the entry was
written under the previous scheme should be detectable. Concretely, either:

  • store_keys::get_pending_swaps returns the value written by the previous revision (["swap1", "swap2"]
    in the reproduction), or
  • the read path reports that legacy entries exist under a different address, instead of returning an empty
    list that is indistinguishable from "nothing was ever persisted".

If the on-disk address is intentionally declared unstable, that should be explicit in the code and covered
by a test that pins the exact bytes for a known key.

Actual behavior

The derived address differs, the lookup misses, and the read path returns an empty list. The entry written
by the previous revision is still in the store, untouched, and is printed by the reproduction alongside the
empty result. Observed output of the executed reproduction (verbatim):

############ RUN 1/2: TARGET f771d1dc (lwk_boltz/src/store.rs from the commit under test)
store.rs sha256: cb332fc5a4b74e065dda8cb991ebc7162088d71b194f0bb661ba72cceb32a6db
running 4 tests
parent nonce (sha256(key)[..12])            : e146c4f7cd4a2a6b240c6d8f
target nonce (DeterministicNonceHash[..12]) : ebfa0a7439b9c223daccc4ed
nonces equal                                : false
=== EXPERIMENT: same-revision round trip ===
store key this revision writes (from its own encrypt_key): 5686bfb1a65456f90adb9735206dbdc3eef430160e232a7fb9163f3e149bbeedd4db6f
written       : ["swap1", "swap2"]
read back     : ["swap1", "swap2"]
=== EXPERIMENT: read entries written by the parent revision ===
parent-revision store key (a87d891, sha256(key)[..12]) : b626c038e65c56398a305db0b690de74716feb63200a8a4ee9776c8096dcee208de9fb
revision-under-test store key (this build)             : 5686bfb1a65456f90adb9735206dbdc3eef430160e232a7fb9163f3e149bbeedd4db6f
keys equal                                             : false
direct lookup under the revision-under-test key         : None
store_keys::get_pending_swaps()                        : []
value written by the parent revision                   : ["swap1", "swap2"]
=== EXPERIMENT: value channel ===
ciphertext len / plaintext len+12+16 : 41 / 41
roundtrip ok                         : true
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

The nonce bytes experiment in the same run reports the two nonce derivations for the plaintext key
boltz:pending_swaps: e146c4f7cd4a2a6b240c6d8f for sha256(key)[..12] versus
ebfa0a7439b9c223daccc4ed for the tagged hash.

Reproduced with:

git clone https://github.com/Blockstream/lwk
cd lwk
git checkout f771d1dc863d7db7221088426d50613c9e3828f0
cargo test -p lwk_boltz --test store_key_upgrade -- --nocapture

keys equal : false
store_keys::get_pending_swaps() : []

Current code at lwk_common/src/store.rs:479 (verbatim):

 let encrypted = encrypt_with_deterministic_nonce(&mut cipher, key.as_ref())

Current code at lwk_common/src/encrypt.rs:119 (verbatim):

 let hash = DeterministicNonceHash::hash(plaintext);

Current code at lwk_common/src/encrypt.rs:120-122 (verbatim):

 let nonce_bytes: [u8; NONCE_LEN] = hash.as_byte_array()[..NONCE_LEN]
 .try_into()
 .expect("nonce slice length validated");

Current code at lwk_common/src/encrypt.rs:15 (verbatim):

 struct DeterministicNonceTag = hash_str("LWK-Deterministic-Nonce/1.0");

The same derivation, before the change: lwk_boltz::encrypt_key at
a87d89122a0631715602908d5be7ed9643f530a6, lwk_boltz/src/store.rs:47-59 (verbatim, removed by
f771d1dc):

pub fn encrypt_key(cipher: &mut Aes256GcmSiv, key: &str) -> Result<String, error::Error> {
 // Derive nonce from key hash (first 12 bytes of SHA256)
 let hash = sha256::Hash::hash(key.as_bytes());
 let nonce_bytes: [u8; 12] = hash.as_byte_array()[..12]
 .try_into()
 .expect("12 bytes from 32 byte hash");
 let nonce = GenericArray::from_slice(&nonce_bytes);

 let mut buffer = key.as_bytes().to_vec();
 cipher.encrypt_in_place(nonce, b"", &mut buffer)?;

 Ok(buffer.to_lower_hex_string())
}

Root cause

The storage address of an entry is the deterministic ciphertext of the plaintext key, so the nonce is part
of the key format. f771d1dc moved the helpers into lwk_common and changed the nonce from
sha256::Hash::hash(key.as_bytes())[..12] to DeterministicNonceHash::hash(plaintext)[..12], the latter
being a SHA256-tagged hash with the tag "LWK-Deterministic-Nonce/1.0"
(lwk_common/src/encrypt.rs:15). The ciphertext — and therefore the address — changes for every key.

Nothing recovers the old address. EncryptedStore::effective_key (lwk_common/src/store.rs:479 at the
current revision, encrypt_key in lwk_boltz/src/store.rs at the reproduced commit) only ever builds the
tagged-hash ciphertext, and the read path treats "key not found" as "no data":
EncryptedStore::get returns Ok(None) on a miss, while store_keys::get_pending_swaps collapses that to
Vec::new() (lwk_boltz/src/store.rs:143 at the reproduced commit:
.map_or_else(|| Ok(Vec::new()), Ok)). There is no fallback lookup under the previous derivation and no
migration step, so the old entries remain on disk but are unreachable through this code path.

At the reproduced commit the change was also undocumented: the doc comments still described the old scheme
(lwk_common/src/crypto.rs:94 "Encrypt a payload using a deterministic nonce derived from the plaintext
SHA256 hash", and lwk_boltz/src/store.rs:41-44 "Uses a nonce derived from the key's SHA256 hash"). In the
current tree those comments have been corrected (lwk_common/src/encrypt.rs:107 now says "plaintext tagged
hash") and the tagged hash is pinned by deterministic_nonce_hash_empty_input_regression
(lwk_common/src/encrypt.rs:171-175) and test_boltz_encryption_key_hash_empty_input_regression
(lwk_boltz/src/store.rs:349), so the new derivation looks intentional — but the loss of the old address,
and the silent empty read that hides it, are unchanged.

Suggested fix

The tagged hash itself does not need to change; what is missing is a path for entries written under the
previous derivation, and a way to notice the miss.

  1. Preferred if any affected build could have been run: make the key-encryption read path
    backward-compatible. On a miss in EncryptedStore::get (and equivalently in the Boltz helpers), retry
    the lookup with the legacy address derived as sha256(plaintext)[..12]; if that hits, return the value
    and optionally rewrite it under the new address. A one-off migration that walks the store for
    legacy-addressed entries and re-keys them would achieve the same without changing every read.
  2. Make the empty result unambiguous. get_pending_swaps/get_completed_swaps currently return an
    empty list both for "never persisted" and for "persisted under the old address", so an upgrade looks
    like a user with no swaps. Returning an error (or at least logging) when a legacy-addressed entry is
    detected would turn a silent data-visibility loss into a diagnosable one.
  3. If the address format is meant to be stable (which the rest of the code implies), guard it. The
    existing test test_default_api_url_keeps_existing_store_keys (lwk_boltz/src/store.rs:311-326 in the
    current tree) asserts that a store written through one handle is read back through another, i.e. store
    keys are treated as a compatibility surface; a test that pins the exact ciphertext for a fixed key and
    cipher (as deterministic_nonce_hash_empty_input_regression already does for the nonce hash) would make
    any future change to the key format an explicit, reviewed decision instead of a silent one.
Dominant language
Rust
Stars
114
Forks
69
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Blockstream/lwk

All issues in Blockstream/lwk

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.