Locked coins
This page shows how to lock some of a wallet’s coins until a block height, follow them while they are locked, and spend them back to the wallet afterwards. It needs libspiffy 5.11.0 or later; quoting the fee of an unlock needs 5.12.0.
A locked coin is a HODLocker output: a script that pays one key, but only to a transaction whose
nLockTime is a block height of at least the lock height. Until the chain reaches that height, nobody can
spend it, the wallet included. libspiffy reads the script with HodlockerLock
(lib/src/core/hodlocker_lock.dart), and builds it with dartsv’s HODLocker template.
How a locked coin fits in the wallet
Section titled “How a locked coin fits in the wallet”- It is the wallet’s. The coin is locked to the key of one of the wallet’s own addresses. An import from the wallet’s seed phrase finds it again: the lock transaction is in the history of the coins that paid for it.
- It is never spent by accident. libspiffy records it as plugin-managed, with
pluginIdhodlocker, so coin selection never picks it for a payment. - It has its own balance.
lockedBalanceonBalanceResponseandBalanceUpdatedEventis the value of the wallet’s locked coins, mined or not. It is not part oftotalBalanceor of any other number there.
// Sketch: assumes an initialized LibSpiffyActorSystem named `libspiffy`.final balance = await libspiffy.coordinator.ask(GetBalanceQuery(walletId: 'alice'));print('spendable ${balance.totalBalance}, locked ${balance.lockedBalance}');Lock coins
Section titled “Lock coins”Send LockCoinsCommand with the amount and the block height the coins stay locked until:
// Sketch: assumes an initialized LibSpiffyActorSystem named `libspiffy`.import 'package:libspiffy/coordinator.dart';import 'package:libspiffy/libspiffy.dart';
/// Locks [amount] sats for about a week: 1,008 blocks of ten minutes.Future<CoinsLockedEvent> lockForAWeek(String walletId, BigInt amount) async { final tip = libspiffy.headerChain.bestHeight; final locked = await libspiffy.coordinator.ask( LockCoinsCommand(walletId: walletId, amount: amount, lockHeight: tip + 1008), ); print('locked ${locked.amount} sats in ${locked.transactionId} ' 'to ${locked.ownerAddress} until block ${locked.lockHeight}'); return locked;}The wallet generates a fresh receive address, pays amount to a HODLocker output locked to its key, and
pays the fee and change like any payment. It records the transaction and broadcasts it. The reply,
CoinsLockedEvent, comes after ARC answers the broadcast, so allow for the 6-minute default timeout.
LockCoinsCommand is refused before anything is built when:
amountis not positive;lockHeightis 500,000,000 or more (larger values are times, which the contract refuses);lockHeightis not above the height of the wallet’s header chain.
The lock height is checked against the headers the wallet holds, so make sure
header sync has caught up before you count blocks from headerChain.bestHeight.
If the broadcast fails after the transaction was built, CoinsLockedEvent.transactionId is still set, and
failure says what ARC answered.
You can also put a locked output in an invoice or a payment of your own: HodlockerOutputSpec(ownerAddress:, lockHeight:, amount:) is an InvoiceOutputSpec. See Multi-output invoices.
List locked coins
Section titled “List locked coins”There is no query for locked coins. Read them from the read model, by their plugin ID:
/// The wallet's locked coins that are not spent or voided.Future<List<BitcoinUtxo>> lockedCoins(String walletId) async { final coins = await libspiffy.walletStorage.getUTXOsByPlugin(walletId, HodlockerLock.pluginId); return coins.where((c) => c.status != UTXOStatus.spent && c.status != UTXOStatus.voided).toList();}Each coin’s pluginMetadata holds its lock: lockHeight (the key HodlockerLock.lockHeightKey) and
ownerAddress. coin.key (txid:vout) is what UnlockCoinsCommand takes, and coin.scriptPubKey is the
locking script as hex. HodlockerLock.parseHex(coin.scriptPubKey) reads the owner’s key hash and the lock
height from the script itself.
Unlock coins
Section titled “Unlock coins”Once the chain reaches a coin’s lock height, UnlockCoinsCommand spends it back to a fresh address of the
wallet, less the fee, and broadcasts the spend:
/// Unlocks every coin whose lock height the chain has reached and that is/// worth more than its unlock costs.Future<void> unlockDue(String walletId) async { final height = libspiffy.headerChain.bestHeight; for (final coin in await lockedCoins(walletId)) { final lockHeight = coin.pluginMetadata![HodlockerLock.lockHeightKey] as int; if (height < lockHeight || coin.status != UTXOStatus.available) continue;
final quote = await libspiffy.coordinator.ask( QuoteUnlockFeeCommand(lockingScriptLength: coin.scriptPubKey.length ~/ 2), ); if (coin.satoshis <= quote.fee!) { print('${coin.key} holds ${coin.satoshis} sats; unlocking costs ${quote.fee}'); continue; }
try { final unlocked = await libspiffy.coordinator.ask( UnlockCoinsCommand(walletId: walletId, utxoKey: coin.key), ); print('unlocked ${coin.key}: ${unlocked.amount} sats back in ${unlocked.transactionId}'); } on CoordinatorFailure catch (failure) { print('${coin.key} not unlocked: ${failure.message}'); } }}The unlock transaction’s nLockTime is the lock height and its one input is not final (sequence
0xfffffffe), as the contract requires. Its input script is <signature> <public key> <preimage>, and the
wallet checks it against the locking script before it records or broadcasts anything.
CoinsUnlockedEvent.amount is what came back to the wallet: the coin less the fee.
UnlockCoinsCommand is refused, with nothing built, when:
- the coin is not one of the wallet’s locked coins;
- the coin is not available, for example still reserved by another unlock (
errorCodecoinsInUse); - the wallet’s header chain is below the lock height, so the network would not take the spend yet;
- the coin holds no more than the unlock’s fee.
The fee of an unlock
Section titled “The fee of an unlock”An unlock carries the whole locking script inside its preimage, so it is large: about 1,300 bytes for the
standard contract. A coin of a few satoshis can cost more to unlock than it holds, and
UnlockCoinsCommand refuses it.
QuoteUnlockFeeCommand(lockingScriptLength:) answers with UnlockFeeQuotedEvent.fee: ARC’s policy rate on
the size HodlockerLock.unlockSize(lockingScriptLength). It builds nothing, so use it to tell a lock worth
unlocking from one that is not, or to warn a user before they lock a small amount. When ARC’s policy can’t
be read, the reply fails with errorCode feeRateUnavailable.
Coins locked to a key outside the account
Section titled “Coins locked to a key outside the account”Some wallets lock coins to a key that is not in the account libspiffy imports, such as a paymail key derived elsewhere from the same seed. An import can’t find those coins: their key is not one of the wallet’s.
Hand such keys to the import as WIFs. ImportWalletCommand(lockKeyWifs: [...]), with xpriv, and
LibSpiffyActorSystem.importWalletFromXpriv(lockKeyWifs: [...]) give the wallet the keys before the scan.
Each key is kept in secure storage, never in the event journal. Its address becomes one of the wallet’s, so
a coin locked to it is found as the wallet’s own, and the wallet signs its unlock with the stored key. A key
of another network is refused. Derive the keys in your app from the seed the account came from.
See also
Section titled “See also”- Commands: Locked coins and Events: Locked coins.
- Script plugins: how plugin-managed outputs are kept out of payments.