20 figuret

###### Abstract

The broad topic of this thesis is the design and analysis of Bitcoin custody
systems – systems to safeguard, manage, and control Bitcoin assets. Both the
technology and threat landscape are evolving constantly. Therefore, custody
systems, defence strategies, and risk models should be adaptive too. We
consider designing for resilience against accidents and attacks, and using
extensible and modular risk models. This way, we support a cyclic process of
design and analysis, where feedback from live deployments can be integrated,
and custody systems can evolve. We begin with a motivating discussion about
the relevance of Bitcoin as a new monetary system with unique features;
censorship-resistance and pseudonymous participation. We explain that custody
systems are the foundation of the Bitcoin economy, upon which all economic
activity depends.

We introduce Bitcoin custody by describing the different types, design
principles, phases and functions of custody systems. We review the technology
stack of these systems and focus on the fundamentals; key-management and
privacy. We present a perspective we call the systems view. It is an attempt
to capture the full complexity of a custody system, including technology,
people, and processes. We review existing custody systems and standards. We
discuss how various risk modelling methods have been applied previously with
custody systems and their components.

We explore Bitcoin covenants, a promising innovation. This is a mechanism to
enforce constraints on transaction sequences. Although previous work has
proposed how to construct and apply Bitcoin covenants, these require modifying
the consensus rules of Bitcoin, a notoriously difficult task. We introduce the
first detailed exposition and security analysis of a deleted-key covenant
protocol, which is compatible with current consensus rules. We demonstrate a
range of security models for deleted-key covenants which seem practical, in
particular, when applied in autonomous (user-controlled) custody systems. We
conclude with a comparative analysis with previous proposals.

Covenants are often proclaimed to be an important primitive for custody
systems, but no complete design has been proposed to validate that claim. To
address this, we propose an autonomous custody system called Ajolote which
uses deleted-key covenants to enforce a vault sequence. Withdrawal from a
vault is subject to a delay period, during which it can be rejected by the
user or automated servers (watchtowers). We argue that this affords a novel
expression of an inherent security-accessibility trade-off that standard
multi-signature custody systems do not support. We evaluate Ajolote with; a
model of its state dynamics, a privacy analysis, and a risk model covering
each phase (setup, operation, and recovery). We propose a threat model for
custody systems which (we argue) captures a realistic attacker for a system
with offline devices and user-verification. We perform ceremony analysis to
construct the risk model.

The thesis offers a synthesis of concepts and methods from sources across
academic literature, industry articles, risk-management methodologies, and
technological practice, and offers several original contributions as mentioned
above. Through integrating whole-system designs with adaptive risk modelling
methods, this thesis commences down a research path towards evolving Bitcoin
custody.

Acknowledgements

I would like to express my gratitude to my supervisor, Prof. Peter McBurney,
who made my journey into computer science not only possible, but a pleasure.
To my early collaborators, Spencer Hommel, Bob McElrath and Bryan Bishop; our
regular discussions propelled my understanding and kept me on the path of
pragmatism, thank you. To my recent collaborators, Antoine Poinsot, Kevin
Loaec, and Edouard Paris; I could not have produced this thesis without the
practical experienced gained from working together with you, merci. I would
also like to thank Dr. Steve Phelps and Patrick McCorry for insightful
feedback in the early stages of my studies.

To my wife, Yaprak, whose boundless support and love kept me inspired and
grounded. Her faith in me made this journey all the more enriching and
fulfilling. To my family, whose encouragement never wavered, I hope to make
you proud. I thank my friend, Arnau, for providing the initial spark that lead
me down this path of study and for being an outstanding example to follow. I
want to thank Wil for encouraging me towards cultivating a practice of wisdom
and ethics, which spurred my well-being alongside this intellectual pursuit.
To Aggelos, whose genius musicianship was an inspiration for many evenings of
respite from our academic endeavours, efcharistó. To the whole community of
friends, colleagues and staff at King’s College London, thank you for helping
me to feel at home.

‘To be free of all authority, your own and that of another, is to die to
everything of
yesterday, so that your mind is fresh, young, innocent, full of vigour and
passion.’
Jiddu Krishnamurti

‘If you know the enemy and know yourself you need not fear the results of a
hundred battles.’
Sun Tzu

‘Amateurs hack systems, professionals hack people’
Bruce Schneier

###### Contents

  1. 1 Introduction
    1. 1.1 Motivation
      1. 1.1.1 Bitcoin, the Disruption
      2. 1.1.2 Money, Currency and Bitcoin
      3. 1.1.3 Evolving Bitcoin Custody
    2. 1.2 Objectives
    3. 1.3 Statement of Originality
    4. 1.4 Publications
    5. 1.5 Thesis Structure
  2. 2 Background Theory
    1. 2.1 Cryptography
    2. 2.2 Bitcoin
      1. 2.2.1 Blockchain Data Structures
      2. 2.2.2 Peer-to-Peer Protocol
      3. 2.2.3 Mining
      4. 2.2.4 Transaction Process
      5. 2.2.5 Governance
      6. 2.2.6 Inputs, Outputs and Script
      7. 2.2.7 Output Types and Addresses
      8. 2.2.8 Taproot and TapScript
      9. 2.2.9 Miniscript and Policy
    3. 2.3 Foundations of Security
    4. 2.4 Key-deletion
    5. 2.5 Protocols
      1. 2.5.1 Network Protocols
      2. 2.5.2 Ceremonies
      3. 2.5.3 Threat Model
  3. 3 Understanding Bitcoin Custody: Technologies, Systems, and Risk Models
    1. 3.1 Introduction to Bitcoin Custody
      1. 3.1.1 Types
      2. 3.1.2 Design Principles
      3. 3.1.3 Phases
      4. 3.1.4 Functions
    2. 3.2 Technology Primer
      1. 3.2.1 Key-management in Theory
      2. 3.2.2 Transaction Coordination
      3. 3.2.3 Bitcoin Network
      4. 3.2.4 Key-management in Practice
      5. 3.2.5 Mixers
    3. 3.3 Systems View
      1. 3.3.1 Existing Systems
      2. 3.3.2 Custody System Standards
    4. 3.4 Modelling Risk
      1. 3.4.1 Overview
      2. 3.4.2 Examples in Custody
    5. 3.5 Conclusion
  4. 4 Bitcoin Covenants
    1. 4.1 Introduction
      1. 4.1.1 Motivation
      2. 4.1.2 Contributions
    2. 4.2 Preliminaries
      1. 4.2.1 Definitions for Covenants
      2. 4.2.2 Covenant Creation and Verification Process
      3. 4.2.3 Signature Message Types
    3. 4.3 Related Work
      1. 4.3.1 Bitcoin Covenant Mechanisms
      2. 4.3.2 Analysis and Applications of Covenants
    4. 4.4 Deleted-key Covenants
      1. 4.4.1 Overview
      2. 4.4.2 Roles and Notation
      3. 4.4.3 Enforcement Conditions
      4. 4.4.4 Protocol Specification
      5. 4.4.5 Potential Applications
    5. 4.5 Security Analysis
      1. 4.5.1 Security Analysis Methodology
      2. 4.5.2 Assumptions
      3. 4.5.3 Threat Model
      4. 4.5.4 Ensure the Integrity of Protocol Enactment
      5. 4.5.5 Protect Honest Participants Against Losses
      6. 4.5.6 Guarantee the Irrevocability of Covenant Enforcement
      7. 4.5.7 Maintain Honest Custodial Control for Covenant Execution
      8. 4.5.8 Analysis Conclusion
    6. 4.6 Designing for Applications
      1. 4.6.1 Composability of Covenant Deposits and Commitments
      2. 4.6.2 Class of Possible Covenants
      3. 4.6.3 Dynamic Fee Allocation
      4. 4.6.4 Safety Concerns
      5. 4.6.5 Fee Strategy
      6. 4.6.6 Proof-of-Reserves
    7. 4.7 Covenant Mechanism Comparison
    8. 4.8 Conclusion
  5. 5 Ajolote: Custody with Bitcoin Vaults
    1. 5.1 Introduction
      1. 5.1.1 Overview
      2. 5.1.2 Covenant Pattern
      3. 5.1.3 Related Work
      4. 5.1.4 Contributions
      5. 5.1.5 Objectives
      6. 5.1.6 Methodology
    2. 5.2 Ajolote System
      1. 5.2.1 Bitcoin key boundaries
      2. 5.2.2 High-level Policies
      3. 5.2.3 Transaction Design
      4. 5.2.4 TapTrees
      5. 5.2.5 Functional Elements
    3. 5.3 Ajolote Setup Procedures
      1. 5.3.1 Pre-requisites
      2. 5.3.2 Mobile Initialisation
      3. 5.3.3 Watchtower Initialisation
      4. 5.3.4 Hardware Signer Initialisation
      5. 5.3.5 Setup Finalisation
      6. 5.3.6 Test Setup
      7. 5.3.7 Conclusion
    4. 5.4 Ajolote Operational Procedures
      1. 5.4.1 Receive
      2. 5.4.2 Vault-deposit
      3. 5.4.3 Withdrawal
      4. 5.4.4 Spend
      5. 5.4.5 Reject
      6. 5.4.6 System health check
    5. 5.5 Ajolote Recovery Procedures
      1. 5.5.1 Decision Tree
      2. 5.5.2 Fall-back
      3. 5.5.3 New Mobile Initialisation
      4. 5.5.4 Signer Account Rotation
      5. 5.5.5 Watchtower Re-initialisation
      6. 5.5.6 Hardware Signer Replacements Initialisation
      7. 5.5.7 Send Bitcoin to New Fall-back
      8. 5.5.8 Re-establish Tier 2
    6. 5.6 Ajolote Evaluation
      1. 5.6.1 Operation Dynamics
      2. 5.6.2 Transaction Sequence Correlation
      3. 5.6.3 Comparison with Multi-signature
    7. 5.7 Ajolote Risk Model
      1. 5.7.1 Assumptions
      2. 5.7.2 Risk Tiers
      3. 5.7.3 Impact
      4. 5.7.4 Threat model
      5. 5.7.5 Authentication
      6. 5.7.6 Setup Security
      7. 5.7.7 Operational Security
      8. 5.7.8 Recovery Security
      9. 5.7.9 Summary
    8. 5.8 Consensus Enforced Covenants
      1. 5.8.1 Two-step Vault-deposit
      2. 5.8.2 Enforcement Security
      3. 5.8.3 Verifying Covenant Enforcement
      4. 5.8.4 Covenant Template Management
      5. 5.8.5 Coin Control
    9. 5.9 Conclusion
  6. 6 Conclusion
    1. 6.1 Contributions
    2. 6.2 Achievement of Objectives
    3. 6.3 Future work
      1. 6.3.1 Custody Systems
      2. 6.3.2 Risk Models
      3. 6.3.3 Vault-Based Custody and Bitcoin Covenants
  7. A Risk Framework for Bitcoin Custody Operation with Revault Protocol
    1. A.1 Connection with Previous Chapters
    2. A.2 Summary
    3. A.3 Introduction
    4. A.4 Overview of Revault Custody Protocol
      1. A.4.1 Revault Architecture Components
      2. A.4.2 Revault Transaction Set
      3. A.4.3 Stakeholders’ Signing Routine
      4. A.4.4 Managers’ Spending Process
    5. A.5 Methodology
      1. A.5.1 Operational Security Models
      2. A.5.2 Attack-Tree Formalism
      3. A.5.3 On Risk Analysis
    6. A.6 Risk Model
      1. A.6.1 Common Attack Sub-Trees
      2. A.6.2 Attack-Trees
    7. A.7 Conclusion

###### List of Tables

  1. 2.1 Fields of a transaction and their meanings.
  2. 2.2 Fields of an output record and their meanings. A Satoshi denotes $10^{-8}$ bitcoin units.
  3. 2.3 Fields of an input record and their meanings. The output hash and output index are often simply referred to as an ‘outpoint’.
  4. 2.4 Table listing relevant Bitcoin Script instructions along with their operation type and a simple description of what it does.
  5. 2.5 Public Key Script templates for standard output types. Instructions are denoted without the OP_ prefix for brevity. Variable data elements are denoted between angled brackets such as <data>.
  6. 2.6 Signature Script and Witness templates for standard output types.
  7. 2.7 Description of Miniscript policies extracted directly from the Miniscript website [8].
  8. 2.8 Summary of attacker capabilities for a ceremony threat model.
  9. 4.1 Data committed to by signatures for each signature hash type when legacy Script semantics for OP_CHECKSIG are used. This includes spending P2PK, P2PKH, P2MS and P2SH output types.
  10. 4.2 Data committed to by signatures for each signature hash type when Segregated Witness version 0 semantics for OP_CHECKSIG are used. This includes spending P2WPKH and P2WSH output types. Note that the ScriptCode is the public key hash for P2WPKH outputs or script hash for P2WSH outputs. (I) means that the commitment is implicit by reference to other explicit commitments.
  11. 4.3 Data committed to by signatures for each signature hash type when TapScript semantics (Segregated Witness version 1) for OP_CHECKSIG are used. This includes spending from P2TR addresses. Note that ‘spend type’ and ‘annex’ are specific to Taproot spending rules and can be used in future upgrades to extend the data committed in signature messages. (I) means that the commitment is implicit by reference to other explicit commitments.
  12. 4.4 Description of attack vectors and their relative difficulty with four generic methods to deleting sensitive data.
  13. 4.5 Comparative summary of strategies for allocating fees to deleted-key covenant transactions.
  14. 4.6 Comparison of the class of possible covenants for several covenant mechanisms.
  15. 4.7 For each proposed soft-fork upgrade, the covenant enforcement subscripts, which are part of the lock script, are shown.
  16. 5.1 The location, storage device, and operational role are shown for each type of key-pair. Non-capital and capital letters represent private and public keys respectively.
  17. 5.2 Miniscript policies and policy fragments in the Ajolote custody system.
  18. 5.3 For each Ajolote output type, the Miniscript policy is shown with its compiled Bitcoin Script.
  19. 5.4 Summary of device state after a successful setup.
  20. 5.5 New state entries after a successful vault deposit.
  21. 5.6 Summary of impact of stolen data.
  22. 5.7 A summary of attacker capabilities per channel type in the Ajolote custody system.
  23. 5.8 Table summarising data used for authentication of entities. In some cases the data depends on additional entities being honest.
  24. 5.9 Summary of new mobile setup and operational state data received across channels. For each data type we show; the source of data, the procedure wherein the data is received, the procedure wherein the data is confirmed with trusted entities and which entities those are.
  25. 5.10 Summary of new hardware setup state data received across channels. For each data type we show; the source of data, the procedure wherein the data is received, the procedure wherein the data correctness is confirmed with trusted entities and which entities those are.
  26. 5.11 Summary of home signer operational state data received across channels. For each data type we show; the source of data, the procedure wherein the data is received, the procedure wherein the data is confirmed with trusted entities and which entities those are.

###### List of Figures

  1. 2.1 Blockchain data structure and the block data type.
  2. 2.2 An example transaction graph. Each input must reference an about from a previous transaction. Some outputs remain unspent.
  3. 2.3 An abstract TapTree with three leaf nodes $A$, $B$, and $C$ which are hashes of three TapScripts. Leaf nodes, branch nodes and the TapTweak are each tagged hashes of data as shown on the right. The TapScript version and size are represented by $ver$ and $size$, respectively. The TapTweak $t$ is the hash of the internal public key $P$ concatenated with the root hash of the Merkle tree $k_{m}$.
  4. 4.1 Diagram depicting a simple covenant. The deposit transaction, $TX^{Dep}$, creates an output with a lock script, $l_{cov}=l_{enf}||l_{cust}$, which contains the set of enforcement public keys $\mathcal{P}$ and custodial public keys $\mathcal{Q}$. The input of the covenant transaction, $TX^{Cov}$, references the output from the deposit.
  5. 4.2 Deleted-key covenants protocol. The enforcer and custodian roles here represent multiple participants while there is only a single depositor. Each enforcer and custodian act independently, though performing the same actions as others with the same role. For example, each custodian will send their public key $Q_{i}$ to the depositor in the first step, and each enforcer will generate their ephemeral key pair $(p_{l},P_{l})$ in the second step. At the termination of this protocol, the custodians have control over a covenant-bound output.
  6. 4.3 A covenant transaction with three inputs that spend outputs in different deposit transactions. Each output commits to an enforcement script $l_{enf}$ and requires sufficient enforcement signatures to be spent. All deposits must be confirmed for the signed covenant transaction to become active.
  7. 4.4 A chain of covenant transactions whose constraints are joint in that each must be satisfied to spend the funds which they control. All covenant transactions with dependent transactions must be non-malleable to protect their dependent transactions from being invalidated.
  8. 4.5 Two covenant transactions which spend from the same deposit output are considered to have disjoint commitments in that either $TX^{Cov}$ $A$ or $TX^{Cov}$ $B$ must be satisfied while the other is invalidated.
  9. 5.1 Entity diagram for the Ajolote custody system. Dashed boundaries represent distinct physical security environments. Solid boundaries represent distinct devices. Inside, their type and primary system function is noted (e.g. type: Hardware signer and function: signer 2). The ‘User’ environment represents the user’s physical location, which often will overlap with their Home or Office environment, and on rare occasions may overlap with the Bank A and Bank B environment. The Bitcoin peer-to-peer network is represented with the dotted box. There are $W$ watchtowers, each in a distinct physical location and physical security environment.
  10. 5.2 Three distinct risk-accessibility tiers in Ajolote. Tier 1; $2$-of-$3$ multi-signature controlled by the user. Tier 2; Vault covenant which can only pay to Tier 2 or Tier 3. Tier 3; $3$-of-$5$ multi-signature controlled by the user.
  11. 5.3 The key-tree for a master key-pair $(q_{n},Q_{n})$ in Ajolote. The master key-pair is generated and stored on the signer. Accounts, $A^{i}_{n}$, are hardened extended public keys to be shared with other signers. The current account is denoted by $i$. The signer may rotate to a new account by deriving a new hardened extended public key, $A^{i+1}_{n}$. Non-hardened public keys for each Ajolote output type are derived from the $i^{th}$ account and depths $h$ or $j$; $R^{i,h}_{n}$, $V^{i,j}_{n}$, $U^{i,j}_{n}$, $F^{i,j}_{n}$.
  12. 5.4 The key-tree for a watchtower’s master key-pair $(w_{k},W_{k})$ in Ajolote. Watchtower accounts, $W^{i}_{k}$, are hardened extended public keys to be shared with other signers. A watchtower may rotate to a new account by deriving a new hardened extended public key, $W^{i+1}_{k}$. Non-hardened public keys are derived from the $i^{th}$ account with depth $j$; $W^{i,j}_{k}$.
  13. 5.5 Transaction (TX) diagram of the Ajolote custody system. Covenant transactions are partially pre-signed; their enforcement subscripts are satisfied. The primary output type is written for each named transaction. These outputs are consumed by the proceeding transaction. Change outputs are not shown here for simplicity.
  14. 5.6 Receive Output TapTree.
  15. 5.7 Vault Output TapTree.
  16. 5.8 Unvault Output TapTree.
  17. 5.9 Fall-back Output TapTree.
  18. 5.10 Mobile initialisation. The final mobile state contains: Ajolote software, Bitcoin master extended key-pair, Noise key-pair, configuration parameters $c$, withdrawal constraints $w$, data to verify PIN and bio-metric tokens.
  19. 5.11 Watchtower (WT) initialisation. The final state of the Ajolote application includes the onion address, Bitcoin public key, and associated service provider for each watchtower; $(O_{k},W^{1}_{k},y)$ $\forall$ $y,k$. The final state of each watchtower includes $(O_{k},w_{k},W_{k},T,w,P^{Noise})$.
  20. 5.12 Hardware signer initialisation. The state of the Ajolote application (on mobile) now includes the complete set of first accounts for hardware signers, $\\{A^{1}_{n}\\}$. The state of the hardware signers includes $\\{A^{1}_{n}\\}$ and $c$.
  21. 5.13 Setup finalisation. The state of the hardware signers now includes $\\{W^{1}_{k}\\}$, $\\{O_{k}\\}$, and $p^{Noise}$.
  22. 5.14 Setup test.
  23. 5.15 Receive. Critically, the communication between the user and counter-party is not mediated by the mobile.
  24. 5.16 Vault-deposit. Protocol to deposit funds into a deleted-key vault covenant in the Ajolote custody system. The mobile and home signer use ephemeral keys to create enforcement signatures for the withdrawal and fall-back transactions that implement ‘vault’ and ‘pay-to-fallback’ covenants.
  25. 5.17 Withdrawal.
  26. 5.18 Spend.
  27. 5.19 Reject.
  28. 5.20 System health check.
  29. 5.21 Decision tree for recovery procedures in Ajolote.
  30. 5.22 Fall-back using the mobile.
  31. 5.23 Fall-back using home signer (if mobile and one other hardware signer are not available). The coordinator entity is any mobile or desktop running Ajolote application in emergency mode.
  32. 5.24 Fall-back without mobile and home signer. The coordinator entity is any mobile or desktop running Ajolote application in emergency mode.
  33. 5.25 Mobile replacement initialisation.
  34. 5.26 Mobile and Hardware Signer (HS) account rotation.
  35. 5.27 Watchtower (WT) re-initilaisation.
  36. 5.28 Hardware signer (HS) replacements.
  37. 5.29 Send bitcoin to new fallback address, $fb^{*}$.
  38. 5.30 Send bitcoin to new receive outputs, $l_{rec^{*}}$.
  39. A.1 Diagram of the transaction (Tx) set structure in the Revault protocol. An Unspent-transaction-output (UTxO) is created by a preceding Tx and is consumed by an input in a proceeding Tx.
  40. A.2 Data flow diagram for the communication of the stakeholders’ signing routine with an example Revault deployment. There are three stakeholders (S) who each have one or two watchtowers (WT). There are two managers (M) and a coordinator. Signature messages, signature requests and watchtower acknowledgements (ACK) are only shown once per connection type but apply to each connection of that type (e.g. there is {$\leftarrow$ signature, $\rightarrow$ ACK} between each WT and S).
  41. A.3 Data flow diagram for the communication of the managers’ spend process. In this example there are two managers (M), three anti-replay oracles (O), five watchtowers (WT) and a coordinator. A Partially-signed Bitcoin Tx (PSBT) is exchanged among managers and between a manager and the anti-replay oracles. A fully signed SpendTx is shared with the WTs through the coordinator.

##  Chapter 1 Introduction

This opening chapter seeks to contextualize and outline the trajectory of our
research into Bitcoin custody systems. These are systems which ensure the
safekeeping and operation of Bitcoin assets, combining cybersecurity measures
with procedural standards. Starting with an examination of Bitcoin’s
disruptive potential and an overview of monetary theory and Bitcoin, we
highlight the compelling economic forces driving the need for development in
Bitcoin custody. This is followed by an explanation of the thesis title. The
key objectives of the thesis are then articulated, accompanied by a statement
of originality and a breakdown of the thesis structure.

###  1.1 Motivation

####  1.1.1 Bitcoin, the Disruption

The control structure of money may be characterized by three dimensions [73];
decentralization of money issuance, decentralization of transaction handling,
and virtualization of representation. The technological innovation that was
introduced to the world with Bitcoin [214] and cryptocurrency technology was
the creation of a form of money with a previously unseen control structure.
Comparisons are often made between Bitcoin and commodity money (e.g. gold),
cash, and commercial bank deposits, however it is fundamentally different to
each of these. The decentralization of money issuance corresponds to a
competitive market between issuers; cash in the fiat system is created in a
monopolistic environment, whereas gold is mined in a competitive industry. If
the transaction handling is decentralized then the asset being transacted is a
bearer instrument; cash is a bearer instrument, while commercial bank deposits
are not. Cash transactions are peer-to-peer, while commercial bank transfers
occur in hierarchical systems. Finally, the representation of a money ranges
from virtual to physical; commodity money and cash are physical, while
commercial bank deposits are virtual. What was previously unseen, that is now
seen in the world of cryptocurrencies, is a form of money that is at the same
time vitrually represented, competitively issued, and whose transactions are
handled by a decentralized network.

Until recently, governments and central banks have been able to maintain a
monopoly over the issuance of currency within their jurisdiction. Their
ability to define what is and what isn’t legal tender has made it difficult
for new currencies to be issued by any entity other than the central banks or
their delegates in lieu of the state. A private company issuing a new
currency, despite for example having a more favourable monetary policy, is
susceptible to coercive pressures which render the currency unattractive for
economic use [150]. With the advent of Bitcoin, the technology to privately
create new forms of money has become available to everyone, as is demonstrated
by the plethora of alternate cryptocurrencies available now. What allows these
systems to persist despite efforts to shut them down or otherwise manipulate
them is the decentralization of the security of the system. A lack of
centralized authority in these systems makes it costly and difficult both
technically and legally for a coordinated attack to cease the operation of a
cryptocurrency.

As society continues on its transition from the industrial age into the
information age, it is plausible that the cyber-economy will continue to grow,
and escape beyond the jurisdiction of nation-states [98]. Privacy technology
will make it ever more difficult to hold entities accountable for avoiding
tax, sanctions, and other forms of capital controls, further incentivising
participation in the cyber-economy. Whether for good or for ill, entities
(individuals, corporations, states) may claim monetary sovereignty by
participating in the cyber-economy, which is available to them regardless of
where they are geographically based so long as they have an internet
connection. While such entities will acquire great freedom in their cyber-
economy participation, they will also be responsible for maintaining their own
security. So understanding the nature of cryptocurrencies; to what extent they
are secure relative to each other and to traditional financial assets, and the
technicalities of securing cryptocurrencies against theft, loss, and death,
will become increasingly important. The fact that so many universities and
financial institutions now have dedicated research and development teams
working with cryptocurrency technology is testament to these arguments.

This technology is inherently a tool for anarchists [282]. What is meant here
by anarchy is not chaos, but rather anti-government. Anarchy in the form of a
network protocol that is used to enable coordination between free and willing
participants, despite perhaps facing coercive pressures against participation.
This technology is radically permission-less; hence it may be used by
revolutionaries, dictators, entrepreneurs, institutions, and democrats alike.
The existence of this technology limits the ability of national gatekeepers to
suppress financial commerce among entities within and across jurisdictions; it
brings optionality to those entities. For example, if a business is operating
within the bounds of a jurisdiction with unfavorable tax laws or capital
controls, they may temporarily store some wealth in a form of money which
transcends national jurisdictions, until they can claim the ‘jurisdictional
arbitrage’ that exists when the business is re-located to a more appealing
jurisdiction. The allure of such a powerful tool will inevitably find its way
into the hands of powerful players.

####  1.1.2 Money, Currency and Bitcoin

The following is a brief analysis of the functions of money, and describes to
what extent these are expressed by Bitcoin in its current state of
development. The purpose is to underline the economic motivations behind the
need for further research and development in Bitcoin custody. Custody, within
the realm of Bitcoin, describes the practices and mechanisms that ensure the
safe holding and secure management of the digital currency, be it for personal
ownership or for an organization or even an application. For non-technical
individuals and organizations to leverage Bitcoin’s benefits, we must
significantly lower the barriers to setting up and using secure custody
systems.

To understand the utility of Bitcoin, one may look at a general framework on
the utility of money, or the ‘functions’ of money, as is commonly described in
economic theory [150]. In 2014 work from the Bank of England [47] an analysis
of the extent to which Bitcoin expresses each of the following functions was
given; a store of value, a medium of exchange, and a unit of account. Since
then, there has been significant progress in the development of Bitcoin, in
associated network applications [63, 241, 106, 99], in the regulatory
landscape which concerns the bridges between the Bitcoin economy and
traditional asset classes, and the institutionalisation of Bitcoin. In order
to illustrate some open areas of research which require more dedicated work,
we present a brief analysis of how Bitcoin expresses each of the functions of
money. The functions of money are commonly thought to operate in a hierarchy
[47]. It should be noted that the expression of these functions is not binary
(on or off), rather, they are expressed along a continuum, which is determined
by the size of a collective of people utilising the asset for these functions.
First, an asset which is to be money must function as a store of value.
Subject to many people using this asset as a store of value, it may then begin
to function as a medium of exchange. Finally, predicated on its use as a
medium of exchange, an asset may function as a unit of account, that is, an
asset whose price is used as a reference price for other goods, commodities
and services.

A unit of account, with which to measure the value of commodities and
services. It is important to realize that valuations are subjective, and so an
asset may function as a unit of account for some people, and not for others.
For those who are accustomed to using fiat currencies as a measure of their
wealth, bitcoin seems like a very volatile asset and thus a poor unit of
account. For those who are disillusioned with the fiat money system, with
beliefs that, in future, scarce digital assets will appreciate in value
relative to other commodities and services, Bitcoin functions as a reliable
measure of their wealth and a unit of account. The question of the extent to
which various people hold such beliefs is out of the scope of this thesis. To
increase the extent to which Bitcoin is used as a unit of account requires
increasing the extent to which it behaves as a medium of exchange and as a
store of value.

A medium of exchange, with which to make payments and contracts for deferred
payments. Bitcoin is a system which comprises both a distributed ledger of the
history of all transactions, and the payment processing network itself [214].
There are some features of this payment network which differentiate it from
traditional payment networks.

Bitcoin is a permissionless payment network, that is, transactions may not be
censored provided appropriate measures are taken regarding privacy and
anonymity. National borders are irrelevant to the processing of Bitcoin
transactions. The availability of the payment network is dependent on a market
mechanism - when there is significant demand for usage of the payment system
the price of transacting (fees) increases. Transactions can be of arbitrary
values, the network is suitable for small (of the same order as fees) and very
large payments. Given the virtual nature of Bitcoin, it is understandable that
the transactions may be augmented with code such that they are subject to
conditions based on authorisation, time, secret knowledge, and combinations
thereof.

The throughput of Bitcoin transactions is limited by design. Transactions are
processed in batches, where one block of transactions is produced, on average,
every 10 minutes. Further, merchants accepting bitcoin payments are encouraged
to wait for multiple blocks (typically six) before considering the transaction
to be immutable. Thus, the settlement properties of Bitcoin are presumably
insufficient for large numbers of very low value transactions which require
immediate finality. There has been significant research into so-called layer 2
applications which leverage a slightly weaker security model for high
frequency, low fee transactions processed externally to the Bitcoin system.
These applications can use the settlement properties of Bitcoin blocks when
disputes arise between users. Examples of such protocols are; the Lightning
Network [102, 241], eltoo [99], and Liquid [63, 106]. Another interesting area
of research is in the potential for the atomic exchange of bitcoin for other
digital resources [103]. Here, an atomic exchange means that either the
payment is made and the digital resource is sent, or no payment is made and no
digital resource is sent. There is no way for either party to cheat the other.

The innovation in payments and contracts is clear. Predicated on beliefs of
Bitcoin functioning as a secure store of value, one may argue that the
technological capability for it to function as a medium of exchange is unlike
any form of money seen before. While there has been significant research and
development in enabling better functionality as a medium of exchange, there is
an argument to be made that the technical research in the design and anlysis
of Bitcoin custody systems is lacking, especially when considering; the
usability requirements of different user groups, the lack of mature open-
source software for resilient cryptographic key management strategies, and the
combination of these strategies with a privacy framework. Presumably, the
asymmetry of knowledge between the public and the technically-literate third-
party Bitcoin custodians is an opportunity for profit, and, so far, these for-
profit companies haven’t made a significant offering of free tools for self-
managed custody systems, which would undermine their business model. However,
Bitcoin behaves as censorship resistant money only if third-party custodians
are not necessary. Self-managed custody enables free participation in the
growing cyber-economy. Individuals, businesses and other organizations should
be capable of self-managed custody to retain Bitcoin’s property of censorship-
resistance as it continues to be adopted globally.

A store of value, with which to transfer ‘purchasing power’ (the ability to
buy goods and services) from today to some future date. The value of bitcoin
at any point in time is based on the aggregate actions of the market
participants in all bitcoin markets. Valuations are subjective, and are often
based on projections into the future about the level of demand that is
anticipated for an asset’s various utilities relative to its supply. Bitcoin
has a finite supply which aids in forecasting the projected value. A store of
value may be expected to retain its purchasing power better under conditions
of high liquidity.

Each holder is in fact utilizing Bitcoin for the function of a store of value.
The bearer nature of bitcoin means that holders are responsible for their own
security. They may outsource this security provision to a third party, such as
a digital asset exchange or web wallet, at the risk of being censored or
defrauded by the operators of those systems. The design space of potential
custody systems is large, given the abundance of operational security
controls, key-management techniques and privacy services available. Defining
specific solutions and enhancing their usability would better enable self-
managed custody and drive adoption of Bitcoin. This thesis aims to examine how
to design and analyse Bitcoin custody systems, to reduce custodial risk and
better enable it to function as a store of value for individuals, businesses,
and institutions. There is a wide array of possibilities to intelligently use
Bitcoin’s programmable nature which (to the best of the authors’ knowledge)
has yet to be reviewed in detail.

####  1.1.3 Evolving Bitcoin Custody

In this section I will explain the title of this thesis, ‘Evolving Bitcoin
Custody’. To begin, custody of Bitcoin is a foundational practice for any
application of the technology. A suite of financial services built on Bitcoin
would not be possible without considering the operational processes for how
the underlying is protected in custody. Applications (to name a few) in
payment networks, international trade, open-timestamps, and as a reserve asset
in the cyber-economy all critically depend on how custody is enacted. A weak
custody system can greatly facilitate compromised services and fraudulent
activity.

This begs the question; what is a strong custody system? A strong custody
system prevents and resists compromise and enables Bitcoin applications to
operate as intended. For the purpose of this thesis, my conjecture is that a
static solution is inappropriate; there is no solution with fixed protections
and mitigating risk controls that can indefinitely remain uncompromised. This
is because of the simple fact that adversaries can and will adapt their
methods. Security is a game of cat and mouse. It is a dynamic arms-race
between the defence and the offence. The defence must out-manouver the
offence, must adapt to new information and learn from mistakes and incidents,
or risk being compromised by the offence. Moreover, as the environment in
which this security game takes place changes (e.g. as Bitcoin’s rules and
capabilities are developed), affording new defence strategies and tactics, the
defence must adapt and utilise new techniques. All this points to the
conclusion that a strong custody system must evolve.

My methods and objectives are thus aimed at contributing to the evolution of
Bitcoin custody systems, and enhancing the capacity for Bitcoin custody
systems to evolve. How? One priority is to design and analyse in the open, and
to elicit feedback from as many interested parties as possible. If a diverse
collection of commercial enterprises use common open tools and technologies,
there will be an incentive for them to collaborate on upkeeping and developing
that foundation. An open process is amenable to a cyclic process of design and
analysis. Open-source technology and open-access research empower and educate
others towards adopting self-managed custody systems. A second priority is to
select methods which support differential analysis for adapting custody
systems and operating environments. For example, selecting a formalism for an
attack model that is modular and can be extended or reduced as needed. In
essence, this thesis encourages open collaboration and promotes dynamic,
adaptable strategies.

###  1.2 Objectives

The objectives of this thesis are as follows:

  * O1

Establish categorical definitions within the domain of Bitcoin custody.
Evaluate existing technology, documentation, standards and analyses. Write an
informed overview to bring coherence to this emerging field of study.

This objective is crucial as it sets the foundation for the rest of the
research. The rapidly evolving nature of the Bitcoin ecosystem necessitates a
comprehensive review and categorization of Bitcoin custody methods and
technologies to ensure subsequent research is built upon an accurate and up-
to-date understanding of the field. This knowledge foundation will be built
and laid out in Chapter 3.

The next objective is central to the research as it seeks to develop and
evaluate novel solutions for managing and mitigating the inherent risks in
Bitcoin custody. One such promising innovation is the use of Bitcoin
covenants, which are specific conditions that constrain bitcoins transactions.
As will be shown, they can be used to both limit fraudulent transactions and
delegate limited operational control to automated systems, and thus enhance
custody systems.

  * O2

Design and analyze a novel covenant protocol that works with state of the art
Bitcoin features. Provide a comparative analysis of alternative covenant
constructions.

As we’ll see, existing covenant constructions rely on features that Bitcoin
does not have, at least not yet. Constructing a covenant with existing Bitcoin
features can open new avenues to improve the security and efficiency of
Bitcoin custody systems. It can also serve as a benchmark and testing ground
when evaluating alternative covenant constructions which may one day be
enabled. This work will be presented and elaborated in Chapter 4.

  * O3

Design and analyse a novel, self-managed custody system for an individual.

Building upon the insights and innovations of the previous chapters, this
objective focuses on the practical implementation of these concepts into a
novel, self-managed Bitcoin custody system called Ajolote. This system,
designed for individual users, will be a demonstration of the practical
application of the theoretical constructs discussed earlier. This objective is
aimed at contributing directly to the field of Bitcoin custody with a
realistic system design, highlighting this research’s practical relevance. The
design and analysis of this system will be presented in Chapter 5.

In summary, the objectives are closely interlinked, each building upon the
previous one, taking us from a comprehensive understanding of the existing
landscape (O1), through innovation and design of new solutions (O2), to the
practical application of these ideas in a novel system (O3). With these, we
contribute to the evolution of Bitcoin custody.

###  1.3 Statement of Originality

The initial research for chapters 4 and 5 were undertaken as a collaboration
between myself, Bob McElrath, Bryan Bishop and Spencer Hommel. The
collaboration began in June 2019 and ended in June 2020 with the release of
our papers titled ‘Bitcoin Covenants: Three ways to Control the Future’ and
‘Custody Protocols using Bitcoin Vaults’. Upon later reflection, I found that
these papers had become out-dated and the presentation and argumentation could
be improved significantly. With the permission from my collaborators I have
re-used many ideas and descriptions from the original papers. However, I have
updated previous work to reflect the current state-of-the-art, added new
insights throughout, improved the methodology, conducted new analyses and
evaluation, and moved from the passive voice to the active voice. The original
papers will remain available online [266, 267].

The work found in appendix A was undertaken as a collaboration between myself
and Antoine Poinsot. This project was part of a broader collaborative effort
to design and build the Revault custody system. Our work together on this
project began in August 2020 and ended in December 2021. This work is
tangential to the primary content of the thesis, offering another relevant
case study of a Bitcoin custody system. The results may be of independent
interest.

###  1.4 Publications

Appendix A was published as presented herein.

Swambo, J., Poinsot, A. (2021). Risk Framework for Bitcoin Custody Operation
with the Revault Protocol. In: Bernhard et al., Financial Cryptography and
Data Security. FC 2021 International Workshops. FC 2021. Lecture Notes in
Computer Science, vol 12676. Springer, Berlin, Heidelberg.
https://doi.org/10.1007/978-3-662-63958-0_1

###  1.5 Thesis Structure

The remainder of this thesis is structured as follows. In chapter 2 we
introduce the background theory in sufficient detail to understand the thesis.
In chapter 3 we offer an introduction to Bitcoin custody with reference to
existing and related work. This includes a technology primer, a systems view
perspective (people, process and technology), and modelling risk. Chapter 4 is
our detailed presentation of a mechanism to construct Bitcoin covenants with
key-deletion. We also describe therein alternative proposals and share a
comparative analysis. With chapter 5 we put forward a custody system design
specification called Ajolote, which uses the deleted-key covenant mechanism.
We evaluate Ajolote, primarily by constructing a detailed risk model and
demonstrating the attack and failure modes. In chapter 6 we offer concluding
remarks which summarise the thesis contributions and highlight directions for
future work. In Appendix A there is associated work on another custody system
called Revault. We provide a risk framework, as a formal attack model, for
that system’s operation. The methodology and findings therein are
complementary with the approach taken in constructing the risk model for
Ajolote.

##  Chapter 2 Background Theory

This chapter describes the foundational theory underpinning the entirety of
this thesis. It commences with an exploration of cryptographic functions
utilized in Bitcoin, alongside an examination of their intrinsic security
properties. Subsequently, Bitcoin itself is analyzed, with a broad discussion
of the blockchain, peer-to-peer protocol, mining, and governance.
Transactions, addresses and outputs are then scrutinized in detail due to
their pivotal role in the technical contributions of this thesis. Moreover,
abstract security strategies and concepts are presented, including the secure
data deletion concept. This is relevant to the covenant protocol detailed in
chapter 4 and later applied in the Ajolote custody system design in chapter 5.

###  2.1 Cryptography

Hash functions are one-way functions that take an input message $m$ and
produce a fixed-length output as a bit-string called the hash value, $h(m)$
[230]. The hash value is typically interpreted as a unique fingerprint for the
message. Hash functions are considered secure if they possess three
properties:

> Pre-image resistance. This refers to the function being one-way. Given
> $h(m)$, it is infeasible to compute $m$.
> Second pre-image resistance. This refers to the the function having weak
> collision resistance. For a given message $m_{1}$ with hash value
> $h(m_{1})$, it is infeasible to compute another message $m_{2}$ such that
> $h(m_{1})=h(m_{2})$.
> Collision resistance. This refers to the function having strong collision
> resistance. For any message $m_{1}$ with hash value $h(m_{1})$, it is
> infeasible to compute another message $m_{2}$ such that $h(m_{1})=h(m_{2})$.

We will see hash functions used frequently as we explore different pieces of
Bitcoin. The hash function used most commonly in Bitcoin is ‘secure hash
algorithm 256’, or simply SHA256 [23]. It outputs a 256-bit string. Another
hash function used in Bitcoin is RIPEMD-160 [108] which outputs a 160-bit
string.

A commitment scheme is another cryptographic primitive that enables us to
commit to a message, $m$, but keep the message itself hidden until sometime
later when we want to prove what our message was [276]. A commitment scheme is
considered secure if the commitments it produces, $C(m)$, are;

> Binding.  The creator of the commitment $C(m)$ cannot compute a different
> message $m^{\prime}$ such that they have the same commitment value,
> $C(m)=C(m^{\prime})$.
> Hiding.  The commitment value $C(m)$ reveals no information about the
> message $m$.

A Merkle tree (also called a hash tree) is an efficient commitment scheme that
repeatedly uses a hash function. It is a data structure that compactly commits
to large data sets. The root of the tree is a commitment (a single hash value)
to each leaf node of the tree. Leaf nodes are hash values from data that will
be committed to. A binary Merkle tree structure is generated by computing the
hash of pairs of leaf and branch nodes until there is a single root hash
value. Any leaf nodes can be revealed and it can be demonstrated that they
were used to produce the tree.

Proof-of-work is a way for a user (the prover) to prove that they have
expended a certain amount of computational effort to others (the verifiers)
[62]. In Bitcoin, proof-of-work is achieved by generating a hash value with a
specific number, $n$, of zeros at the beginning of the bit-string. The higher
$n$ is, the more difficult it is to generate a valid hash value because (on
average) it takes more guesses at messages to compute a bit-string with more
leading zeros. The security of proof-of-work depends on the pre-image
resistance of the hash function. The verification of a proof-of-work only
requires computing the hash value given the message, which is trivial.

Public-key cryptography (or asymmetric cryptography) is the basis on which
bitcoin is securely held and transacted. Contrary to symmetric cryptography
schemes, where entities share a secret key to perform tasks such as encryption
and message authentication, in an asymmetric cryptography scheme each entity
has both a public key (which may be shared) and a private key (which must be
kept hidden). Public-key cryptography is based on the intractability of
certain mathematical problems. Key-pairs are generated using a one-way
function. It is easy to compute the public key given the private key, but
infeasible to compute the private key given the public key.

In Bitcoin, public-key cryptography is used for digital signatures based on
the mathematics of elliptic curves over finite fields. The approach leverages
a hard mathematical problem that arises from the algebraic structure of
elliptic curves over finite fields. Specifically, the security of the digital
signature schemes used in Bitcoin depend on the hardness of the Elliptic Curve
Discrete Lograithm Problem (ECDLP). Let us briefly consider how to derive a
Bitcoin key-pair.

Bitcoin uses a specific standardized set of constants which define the
elliptic curve, known as ‘secp256k1’ [20]. A private key, $k$, corresponds to
a random integer. The public key, $K$, corresponds to a point on the elliptic
curve. It is computed by elliptic curve point multiplication of the private
key with the generator point of the curve, $G$,

$K=kG$ (2.1)

Multiplication on an elliptic curve over a finite field is easy to calculate
one-way, but difficult to invert. Thus, deriving the public key from the
private key is simple, but deriving the private key from the public key is
assumed to be an intractable problem (given sufficiently large numbers),
called the Elliptic Curve Discrete Logarithm Problem.

Bitcoin supports two digital signature schemes that rely on the same elliptic
curve. Key-pairs are compatible with both schemes. These are the Elliptic
Curve Digital Signature Algorithm (ECDSA) [22] and the Schnorr Signature
algorithm [261]. These signature schemes provide powerful security services.
Specifically, they provide:

> Message integrity.  A signed message cannot be changed without invalidating
> the signature.
> Message authentication.  A signature generated with a private key owned by a
> user shows that the message was sent by that user.
> Nonrepudiation.  The signer of a message cannot deny that they have signed
> the message.

Schnorr signatures, in particular, offer several advantages over ECDSA due to
their mathematical linearity. This property of Schnorr signatures simplifies
and enhances several cryptographic operations, which we will now discuss:

  * Public Key Aggregation: Schnorr signatures allow for the aggregation of multiple public keys into a single public key that can be used to verify a signature that represents a group of signers.

  * Signature Aggregation: Similarly, Schnorr signatures allow for the aggregation of multiple signatures into a single signature. This is beneficial in scenarios when multiple entities need to sign a single transaction.

A concept that is particularly relevant for Bitcoin custody is key derivation.
A key derivation function $KDF$ is simply a method to take an established key,
$K_{1}$, and compute from it a new key $KDF(K_{1},r)=K_{2}$ where $r$ is some
random value. Key derivation can be used for private and public keys. By using
a one-way function in the implementation of $KDF$, the key derivation cannot
be reversed. This is useful when re-using public keys could cause a problem,
as is the case in some cryptography protocols which were designed for single-
use session keys. As a general principle in cryptography, it is always better
to use fresh keys where possible. Re-used keys can create statistical
correlations that enable cryptanalysis techniques to weaken or break, for
example, digital signatures.

For a detailed exposition of cryptography engineering, readers are referred to
the classic textbook ‘Understanding Cryptography’ by C. Par and J. Pelzl
[230]. For an overview of cryptography in Bitcoin readers are referred to
‘Mastering Bitcoin’ by A. Antonopoulos [55].

###  2.2 Bitcoin

Bitcoin is a system built on a combination of numerous information technology
mechanisms. It was introduced by S. Nakamoto [214] and has since been
described in systematic detail by A. Antonopoulos [55] and others. In the
following, let us prepare for the main content of this thesis by reviewing how
it works.

####  2.2.1 Blockchain Data Structures

A blockchain is a data structure that holds a historical record of
transactions. It is used as a public ledger from which the balances of users
can be derived and new transactions can be verified. As the name indicates,
the data structure is a chain of blocks and is shown in figure 2.1. Blocks are
ordered and timestamped. Each block contains a block header and batch of
transactions. A block is uniquely identified by a block hash, which is the
SHA256 hash of its block header. Blocks are given a deterministic ordering by
including the previous block hash in the block header. The transactions
contained in a block are set as leaves in a Merkle tree. The root of this
tree, called the Merkle root, is included in the block header. This is a
binding commitment between the complete batch of transactions and this
particular block in a manner that allows users to verify which transactions
are included. Transactions can’t be modified, added or removed without
altering the Merkle root, and consequently the block hash. Finally, a nonce is
included in the block header as a variable field to allow block creators to
generate a proof-of-work using the block hash. Bare this in mind when we
consider mining and the consensus mechanism.

Figure 2.1: Blockchain data structure and the block data type.

Users create, digitally sign, and broadcast transactions to send bitcoin among
each other. Transactions are objects with a specific data structure, described
in table 2.1. Note that the intuitive concept of accounts and balances is not
directly encoded into the blockchain nor into transactions. Instead, unspent
transaction outputs (UTXOs) are tracked and designated to a specific address
controlled by users. Each transaction has a set of inputs and a set of
outputs. The inputs reference existing UTXOs created in previous transactions,
to be consumed in the current transaction, as shown in figure 2.2. The outputs
set the target address and amount for each new UTXO being created. The total
amount of the inputs must be greater or equal to the total amount of the
outputs. The difference is offered as a transaction fee. Transactions will be
further detailed in 2.2.6.

Transaction Field |  Meaning
---|---
Transaction ID |  Unique identifier
Version |  Transaction data format version
Inputs |  A list of 1 or more transaction inputs
Outputs |  A list of 1 or more transaction outputs
Witnesses |  A list of witnesses (unlocking scripts), up to one for each input (may be empty)
Locktime |  The block number or timestamp at which this transaction becomes valid
Table 2.1: Fields of a transaction and their meanings. Figure 2.2: An example
transaction graph. Each input must reference an about from a previous
transaction. Some outputs remain unspent.

At any given block, the complete set of UTXOs can be derived by stepping
through the historical record up to and including that block while tracking
which UTXOs have been consumed and which haven’t. The UTXO set is required to
validate new transactions; to avoid double-spending attempts and to prevent
creating bitcoin out of nothing. Users need only track the UTXO set for the
current block to determine the validity of new transactions. A user need only
download and verify the historical record once (this is called synchronising),
and the resulting UTXO set can be relied on from then on.

####  2.2.2 Peer-to-Peer Protocol

The Bitcoin network consists of a distributed set of peers who establish
connections among each other to send and receive block data. Moreover, each
peer validates and verifies block and transaction data according to consensus
rules, rejecting data when the rules are violated. What emerges from the
actions of individual peers is a distributed consensus protocol to manage the
blockchain state. Any internet connected device can join the peer-to-peer
network. The network is not hierarchical, each peer acts as both client and
server to others.

Network discovery messages, transaction and block announcements, requests and
delivery of transactions and blocks are all part of the protocol. Peers will
track the transactions they receive if they are valid, and forward them to
other peers. The pool of transactions tracked by a peer is called the memory
pool. The protocol includes a multitude of methods to mitigate denial-of-
service attacks on peers, such as limiting the size of their memory pool and
temporarily banning connections with peers that violate consensus rules.

####  2.2.3 Mining

A certain type of node in the network will participate as a miner. A miner’s
role is to collect transactions from the peer-to-peer network (and elsewhere
in some cases), build a valid block containing them, and propose the block to
the network. Miners must produce a proof-of-work with the block hash for the
block to be accepted. At any given time there is a difficulty parameter in the
global state which determines the difficulty of producing the next valid
proof-of-work.

Since producing proof-of-work is costly for the miner (computational effort
requires energy expenditure), they require an incentive to perform this
service for the network. The incentive is payment in bitcoin. If a block
constructed by a miner is accepted by the network, all transaction fees and a
block subsidy will be paid to the miner. The block subsidy is newly issued
bitcoin units (on a schedule that will eventually decay to zero).

Anyone can participate as a miner. If the payment is greater than the cost, a
rational player would start mining. The difficulty parameter is increased if
throughput over a span of 2016 blocks is faster than the target; one block per
ten minutes. Conversely, it is decreased if the throughput is less than the
target. The difficulty adjustment makes the system resilient. Why?

It is necessary to impose a throughput limit that gives sufficient time for
the peer-to-peer network to distribute and verify block data. The limit
generally prevents distributed denial-of-service attacks wherein the network
peers are overwhelmed by new blocks. Moreover, if throughput was too high, it
would result in consensus instability with many forks [101]. A fork is when
more than one valid and competing blocks are observed. A fork can persist,
with several blocks competing against several others. The consensus rules
determine how to select from multiple versions of the blockchain if a peer is
presented with conflicting but valid states. The fork-selection consensus rule
is to consider the blockchain with the most cumulative proof-of-work as the
canonical chain. Nonetheless, blockchain forks can be frustrating to users
because new transactions become less reliable. Thus, mechanisms to reduce the
frequency of forks are important.

On the other hand, if the difficulty makes the cost of producing a proof-of-
work higher than the reward, rational players will stop mining. This will
reduce throughput below the target. This is also frustrating for users whose
transactions will take more time. By systematically reducing the difficulty
once the throughput is low, the system incentives become compatible once more
for rational miners.

####  2.2.4 Transaction Process

In this example exchange, we detail the process by which Alice sends Bob 1
BTC. This example is designed to elucidate the interactions between users,
their bitcoin applications, and the underlying peer-to-peer network, building
on the concepts discussed so far.

  1. 1.

Setup:

    1. (a)

Bob opens his bitcoin application and ensures it is synchronized with the
blockchain.

    2. (b)

He observes a balance of 0 BTC.

    3. (c)

Bob generates a new receiving address and securely shares it with Alice.

  2. 2.

Initiation of Transfer:

    1. (a)

Alice opens her bitcoin application and verifies synchronization with the
blockchain.

    2. (b)

Her balance reads 1.5 BTC.

    3. (c)

Using the ‘Send’ feature, she initiates a transfer of 1 BTC to Bob’s provided
address.

    4. (d)

Her application constructs and signs the transaction, then broadcasts it to
her 8 connected peers.

  3. 3.

Peer Validation:

    1. (a)

Each of Alice’s peers checks the transaction against consensus rules.

    2. (b)

Upon validation, they verify Alice’s signature.

    3. (c)

Valid transactions are retained in memory and relayed to each peer’s
respective connections, allowing the transaction to propagate through the
network.

  4. 4.

Mining and Block Inclusion:

    1. (a)

Miners, also peers, receive the transaction and perform the same validation
process.

    2. (b)

Considering transaction fees, miners decide whether to include Alice’s
transaction in the next block they attempt to mine.

    3. (c)

A successful miner, one who generates a valid proof-of-work, includes Alice’s
transaction in a valid block. The miner broadcasts this block.

  5. 5.

Block Propagation:

    1. (a)

Peer nodes, upon receiving the new block, validate its contents and the
embedded transactions.

    2. (b)

Nodes append validated blocks to their blockchain copies and relay the block.

    3. (c)

The block diffuses throughout the network, reaching all nodes, including those
of Alice and Bob.

  6. 6.

Balance Update:

    1. (a)

Alice’s application reflects her new balance, reduced by 1 BTC and the
associated transaction fee.

    2. (b)

Bob’s application updates his balance, showing 1 BTC.

This example captures the intricacies of peer-to-peer exchanges within the
Bitcoin network, shedding light on the multiple processes that ensure secure
and accurate transactions.

####  2.2.5 Governance

The consensus rules of Bitcoin can only be changed given widespread support
among participants in the system. There needs to be sufficient consensus about
changing the rules of consensus. This is a difficult process that is not
strictly formalised. As Bitcoin has become more widely adopted and the economy
building on it has grown, it seems to have become increasingly difficult to
change the consensus rules. There are two types of consensus rule changes. A
hard-fork is a change that makes previously invalid blocks valid. Without
unanimous agreement to abide by the new rules the network would separate into
two factions because any peers abiding by the old rules will reject a certain
type of block as invalid, while peers following the new rules will accept
them. A soft-fork is a change that makes previously valid blocks invalid. A
soft-fork is considered to be backwards-compatible because peers following the
old rules will accept blocks made according to the new rules. A soft-fork
still puts peers following old rules at risk because they may accept a block
that is no longer accepted by those following the new rules. However, due to
the fork-selection rule, if a majority of miners are producing blocks
according to the new rules, this non-consensus block would be discarded once
the chain of blocks that are valid for all peers becomes longer. Soft-forks
are the preferred method for updating the consensus rules but they do not come
without risk. Proposals for soft-forks should be well specified (for example,
as a Bitcoin Improvement Proposal (BIP) [270]) and their implementation should
be widely and thoroughly reviewed.

####  2.2.6 Inputs, Outputs and Script

In preparation for later chapters we will need to understand how transactions
are verified. Note that coinbase transactions used by miners to issue new
bitcoin will be ignored for this discussion. We saw the transaction data
structure in 2.1. Now, tables 2.2 and 2.3 describe an input and output record
respectively. Transactions are entries to the public ledger that reassign
ownership of Bitcoin. The strict controls over reassigning ownership of
Bitcoin are based on digital signatures and additional programmable
constraints. Inputs and outputs contain code written in a language
specifically designed for Bitcoin called Script.

Output Fields |  Meaning
---|---
Amount |  Number of Satoshis being assigned to the public key script
Script length |  Length of the public key Script
Public key Script |  Expression of conditions (or a commitment to them) that need to be satisfied to consume this output
Table 2.2: Fields of an output record and their meanings. A Satoshi denotes $10^{-8}$ bitcoin units. Input Fields |  Meaning
---|---
Output hash |  The hash of the referenced transaction containing the output
Output index |  The index of the specific output in the referenced transaction
Script length |  The length of the signature Script
Signature Script |  Script for confirming transaction authorization
Sequence |  Optionally signals ‘replace-by-fee’ [148], optionally encodes a relative time-lock [80]
Table 2.3: Fields of an input record and their meanings. The output hash and
output index are often simply referred to as an ‘outpoint’.

Script is a stack-based language [15]. It was designed to support stateless
verification of Bitcoin transactions. Here, ‘stateless verification’ refers to
the fact that no state information, or contextual data about the system, is
required prior to the execution of Script and no such information is retained
post-execution. Importantly, Script is not Turing complete, as it lacks the
ability to perform loops or complex conditional logic (e.g. go-to). This
inherent limitation allows for easier reasoning about the potential
termination of a Script program, be it successful or otherwise [57]. To
clarify, Script is constructed such that it cannot diverge or run
indefinitely, further reducing the risk of computationally intensive
executions that could potentially lead to denial-of-service attacks on network
peers and miners as they verify transactions. A subset of relevant Script
instructions is provided for reference in table 2.4.

Script Instruction | Operation Type |  Description
---|---|---
OP_CHECKSIG | Cryptography |  Verifies a signature against a public key and pushes the result (1 if the check succeeded, 0 if it did not) onto the stack
OP_CHECKSIGVERIFY | Cryptography |  Verifies a signature against a public key and if the result is not true, the script fails
OP_CHECKSIGADD | Cryptography |  Verifies a signature against a public key and adds a numerical result to the stack
OP_CHECKMULTISIG | Cryptography |  Verifies multiple signatures against multiple public keys
OP_HASH160 | Cryptography |  Hashes the top stack item with SHA-256, then with RIPEMD-160
OP_CHECKLOCKTIMEVERIFY | Time Lock |  Verifies if the transaction’s lock-time is greater than or equal to the top stack item
OP_CHECKSEQUENCEVERIFY | Time Lock |  Verifies the relative lock-time (set using the sequence number) of the transaction based on the top stack item
OP_NUMEQUAL | Numeric |  Checks if the top two stack items are numerically equal, pushes the result to the stack
OP_DUP | Stack Operations |  Duplicates the top stack item
OP_EQUALVERIFY | Stack Operations |  Checks if the top two stack items are equal, fails if not
OP_EQUAL | Stack Operations |  Checks if the top two stack items are equal, pushes the result to the stack
OP_0 | Push Value |  An empty array of bytes is pushed onto the stack
OP_1 | Push Value |  The number 1 is pushed onto the stack
OP_IF | Control |  If the top stack value is not False, the statements are executed
OP_VERIFY | Control |  Marks transaction as invalid if the top stack value is not true
OP_RETURN | Control |  Marks transaction as invalid
Table 2.4: Table listing relevant Bitcoin Script instructions along with their
operation type and a simple description of what it does.

The Sequence field in a Bitcoin transaction input has a dual role. It can be
used to signal ‘replace-by-fee’ (RBF) or to encode a relative time-lock.
Introduced in BIP 125 [148], RBF is a method that allows an unconfirmed
transaction in a node’s memory pool to be replaced with a different
transaction that spends at least one of the same inputs and pays a higher
transaction fee111If the Sequence number of an input is less than 0xffffffff -
1, then it signals that the transaction can be replaced.. Introduced in BIP
112 [80], relative time-locks allow an input to specify a minimum time or
block height difference from when the output being spent was included in a
block. The transaction output can’t be spent until a certain time period has
passed since the output was included in a block222If the Sequence number of an
input is less than 0xfffffffe, and the version of the transaction is 2 or
higher, then the Sequence number is interpreted as a relative lock-time.. To
create a relative lock-time, the sequence field is used in conjunction with
the OP_CHECKSEQUENCEVERIFY instruction.

Although Script’s syntax – the set of rules that parse byte strings into
instructions – is consistently applied, its semantics, or the consensus rules
that govern instruction interpretation and execution procedure, can vary based
on the context. ‘Context’ here is referring to the specific output type, as
will be described in the following subsection. One method to make these
contextual differences more manageable is through the concept of ‘lock’ and
‘unlock’ Scripts. ‘Lock’ Scripts can be understood as conditions set in a
Bitcoin transaction output, which must be fulfilled for the transaction output
to be spent. Conversely, ‘unlock’ Scripts, or scripts provided in the
transaction redeeming the locked output, serve to fulfill these conditions by
providing the required data or signatures. During the process of verifying a
transaction, the unlock script is executed first, followed by the lock script,
with the remaining stack elements from the execution of the unlock script. The
transaction is considered valid if the lock script execution is completed
successfully, without any errors. The ‘context’ determines how the lock script
is committed within an output and outlines where both the lock and unlock
scripts are provided within the transactions.

Each output specifies an amount and a public key script333In the reference
implementation this is called the scriptPubKey.. The public key script will
either be a lock script, or a commitment to a lock script. In the latter case,
the lock script has to be provided in a subsequent transaction that consumes
this output. The locking conditions are represented as a Script program with
data and/ or instructions to manipulate stack elements during execution. The
owner of an unspent transaction output (UTXO) is anyone or any group who can
satisfy its locking conditions with a valid unlock script which typically
depends on secret information. The unlock script is provided in the subsequent
transaction redeeming the output balance. Transactions have two containers for
the unlock script. The first is the signature script444In the reference
implementation this is called the scriptSig in the input, and the second is
the witnesses field in the transaction. Next, we will describe when and why
these different containers are used for Script verification.

####  2.2.7 Output Types and Addresses

There are 8 output types that are considered standard (as of Bitcoin version
23.0). The default policy for nodes in the network is to relay transactions
with standard outputs only. Note that this is not a consensus rule, but it is
broadly enforced. These output types each have a different purpose and are
specified as a public key script template, with fixed instructions but
variable data elements. These are shown in table 2.5. The corresponding script
template in a transaction spending from the given output types is shown in
table 2.6 with the location where the script is contained. These templates may
encompass both unlock and lock scripts.

Output Type | Public Key Script Template
---|---
pay-to-public-key (P2PK) | <public key> CHECKSIG
pay-to-public-key-hash (P2PKH) | DUP HASH160 <public key hash> EQUALVERIFY CHECKSIG
pay-to-script-hash (P2SH) | HASH160 <lock script hash> EQUAL
pay-to-multi-signature (P2MS) | 2 <public key A> <public key B> <public key C> 3 CHECKMULTISIG
null-data | RETURN <data>
pay-to-witness-public-key-hash (P2WPKH) | 0 <20-byte public key hash>
pay-to-witness-script-hash (P2WSH) | 0 <32-byte script hash>
pay-to-taproot (P2TR) |  key path: 1 <32-byte public key>
|  script path: 1 <32-byte witness program>

Table 2.5: Public Key Script templates for standard output types. Instructions
are denoted without the OP_ prefix for brevity. Variable data elements are
denoted between angled brackets such as <data>.

The output types P2PK, P2MS, and null-data are incorporated in the tables for
the sake of comprehensiveness. However, it’s important to note that P2PK and
P2MS have been largely replaced by more recent standard output types.
Additionally, the null-data outputs, while part of the Bitcoin protocol, offer
limited practical utility for our purposes and hence, will not be elaborated
upon in subsequent discussions.

An address is derived from the public key script in a particular way depending
on the output type. It is a string of characters that users must share in
order to receive a payment and it includes version information, a commitment
to the lock script and a checksum for error detection. There are several types
of address corresponding to different output types, each with a different
purpose. Addresses are created by users and can be controlled independently or
collaboratively. Now, let’s consider common address/output types and elaborate
on how ‘ownership’ of bitcoin is defined.

Output Type |  Template | Location
---|---|---
pay-to-public-key (P2PK) |  <signature> | Signature Script
pay-to-public-key-hash (P2PKH) |  <signature> <public key> | Signature Script
pay-to-script-hash (P2SH) |  <arbitrary unlock script> <serialised lock script> | Signature Script
pay-to-multi-signature (P2MS) |  0 <signature A> <signature B> | Signature Script
null-data |  |
pay-to-witness-public-key-hash (P2WPKH) |  <signature> <public key> | Witnesses
pay-to-witness-script-hash (P2WSH) |  <unlock script> <serialized lock script> | Witnesses
pay-to-taproot |  key path: <signature> | Witnesses
(P2TR) |  script path: <tapleaf unlock script> <serialised tapleaf lock script> <control block> | Witnesses
Table 2.6: Signature Script and Witness templates for standard output types.

A P2PKH output type commits to a public key by including the public key hash
in the public key script. A user who has received payment to their P2PKH
address can spend these coins by providing both their public key and a digital
signature in the signature script of their transaction. To create a valid
digital signature, the user must have access to the private key associated
with the public key. Users can openly share their P2PKH address. Their public
key will remain hidden until they spend from the address, at which point they
must reveal their public key.

A P2SH output type commits to a lock script by including the hash of the
serialised lock script in the public key script [53]. This output type was
made standard in 2012 and it allows the receiver to define and share the
locking script without revealing what that script is (at least until spending
from it) [54]. Spending a P2SH output requires providing the exact script that
produced the hash as well as a valid unlock script (typically with signatures)
in the signature script of a new input. The execution logic of Script when
spending from a P2SH address is modified. First, the provided lock script is
checked against the script-hash commitment in the address. Subsequently,
standard execution proceeds wherein the unlock script is executed first,
followed by the execution of the lock script, utilising any remaining stack
elements left by the unlock script.

With the soft-fork called the ‘Segregated Witness soft-fork’, several
consensus rules were added to Bitcoin [191]. These rules enabled the
separation of a transaction’s data representing its effects (on blockchain
state) from its ‘witness’ data (the unlock script) required for validation.
Consequently, a new class of ‘Segregated Witness’ (SegWit) transactions were
enabled. These transactions offer enhanced storage and bandwidth efficiency
and make use of an updated semantics of Script. This is the reason for having
two containers for the unlock script. Standard SegWit outputs can be redeemed
by setting an empty signature script and instead placing signatures and the
unlock script in the witness field. There are two version 0 SegWit output
types that are equivalent to P2PKH and P2SH. These are called pay-to-witness-
public-key-hash (P2WPKH) and pay-to-witness-script-hash (P2WSH).

The implementation of the ‘Taproot’ soft-fork introduced several additional
consensus rules to Bitcoin. For all output types, with the exception of P2TR,
the Elliptic Curve Digital Signature Algorithm (ECDSA) is employed. However,
in the case of P2TR, the Schnorr digital signature algorithm is utilized
[288]555In both instances, the elliptic curve secp256k1 is used, and private
keys are compatible.. The linearity of Schnorr signatures simplifies both
public key aggregation and signature aggregation. This means that
collaborative control of outputs, which previously required multiple
OP_CHECKSIG instructions in Scripts, can now be achieved more privately,
reducing storage and bandwidth costs for the network.

Furthermore, the linearity property enables the commitment of lock scripts by
adding them to a public key, a process known as a ‘public key tweak’. This
results in the output type being represented as a public key, effectively
concealing the fact that a script was committed to, at least until the output
is spent. In essence, P2TR output types amalgamate behaviors akin to P2PK,
P2MS, and P2SH into a single, more efficient output type. The technical
constructions in chapters 4 and 5 both utilise P2TR outputs and so let us
explore these in more detail.

####  2.2.8 Taproot and TapScript

This section provides an overview of the key concepts from the Taproot [291]
and TapScript [289] specifications that are pertinent to this thesis. While
many low-level details are omitted for brevity, interested readers can find
comprehensive information in the cited specifications.

Recall from Table 2.2 that an output record contains a ‘public key script’
field, which holds a commitment to the lock script. More specifically, the
structure of the values in the public key script determines the output type,
such as P2PKH, P2WSH, and others. In this section, we focus on P2TR output
types. A Taproot output type is structured as follows:

$public\text{ }key\text{ }script:\text{ }<witness\text{ }version>\text{
}<taproot\text{ }output\text{ }key>$

Here, the witness version is 1, and the Taproot output key is a 32-byte public
key as defined in the Schnorr specification for Bitcoin [288]. The Taproot
output key, denoted as $q$, encodes a commitment to both a key-path spend
option and script-path spend options. It is the $x$ component of $Q$, where

$Q=P+int(t)G$ (2.2)

In this equation, $P$ is an internal public key, $G$ is the elliptic curve
base point, and $t$ is the TapTweak hash cast to an integer. The internal
public key is used for key-path spending. To ensure domain separation, so-
called ‘tagged hashes’ are used. The notation is

$hash_{tag}(x)=SHA256(SHA256(tag)||SHA256(tag)||x)$ (2.3)

for arbitrary data $x$ and a string $tag$. Here, $||$ denotes concatenation.
This approach theoretically reduces the likelihood of hash collisions within
the system [291]. The TapTweak hash contains a commitment to a tree of
TapScripts that can be used in script-path spending. It is a hash of the root
$k_{m}$ of a Merkle tree [209], known as the TapTree, and $P$,

$t=hash_{TapTweak}(P||k_{m})$ (2.4)

To comprehend how script-path spending operates, we need to understand the
TapTree data structure. An example is depicted in Figure 2.3. The structure’s
purpose is to compactly commit to distinct data sets and enable existence
proofs for a data set without revealing the others. It is a Merkle tree, also
known as a Hash tree. A TapTree is a binary tree that may be unbalanced. Each
leaf node is the hash of a ($\tt leaf$ $\tt version$, $\tt TapScript$) tuple.
Each TapScript is a distinct lock script that can be satisfied to spend the
output. Each branch node is the hash of its two child nodes. The root node is
the Merkle-root hash, $k_{m}$, which is a deterministic derivation from the
given leaf nodes.

Figure 2.3: An abstract TapTree with three leaf nodes $A$, $B$, and $C$ which
are hashes of three TapScripts. Leaf nodes, branch nodes and the TapTweak are
each tagged hashes of data as shown on the right. The TapScript version and
size are represented by $ver$ and $size$, respectively. The TapTweak $t$ is
the hash of the internal public key $P$ concatenated with the root hash of the
Merkle tree $k_{m}$.

In this thesis, we are primarily interested in script-path spending. Key-path
spending does not enable the complex access policies or privacy guarantees we
seek. Therefore, we must use an internal public key with an unknown private
key to prevent key-path spending. A method for this was described in the
Taproot specification [291], stating that one should use ‘the hash of the
standard uncompressed encoding of the secp256k1 base point $G$ as $X$
coordinate’. The intuition here is that the hash function produces a random
value, based on a ‘nothing-up-my-sleave’ number, and so the resulting public
key was not generated from a known private key in the standard way, by
computing $P=pG$. Given the internal public key, one cannot find the private
key without solving the elliptic curve discrete logarithm problem which is
assumed to be hard.

A transaction that consumes a Taproot output as its input must provide a
witness with a specific structure that satisfies the chosen TapScript. The
witness structure has the form

$script-path\text{ }witness:\text{ }<initial\text{ }stack\text{
}elements>\text{ }<TapScript>\text{ }<control\text{ }block>$

The initial stack elements are the unlock script (typically containing all
signatures). The TapScript is the chosen lock script that must be present as a
leaf node in the TapTree. The control block contains the internal public key
$p$ and a proof of the existence of the TapScript in the TapTree. The Merkle
proof contains all necessary hashes to derive $k_{m}$, but doesn’t reveal
unused TapScripts. For example, in Figure 2.3, the inclusion proof to spend
with TapScript C includes the hashes B and A.

When the script-path witness is broadcast as part of the transaction, it
becomes public knowledge. The control block reveals a minimum depth of the
complete TapTree. The TapScript reveals public keys and system parameters such
as the length of time-locks.

####  2.2.9 Miniscript and Policy

Miniscript is a language designed to be decoded into Bitcoin Script [8]. Its
primary aim is to simplify the process of writing Bitcoin Script as generic
access policies, which are composed of common subpolicies such as signature
verification, time-locks, and hash-locks. Miniscript enhances the analysis of
spending cost, script size, and correctness.

In practical terms, an engineer-readable form is used to write a policy, which
is then compiled to generate the corresponding Miniscript. This Miniscript
directly maps to Script, which is subsequently used in Bitcoin transactions. A
reference of the Miniscript policies utilized with the Ajolote custody system
is provided in Table 2.7.

Policy |  Description
---|---
pk(NAME) |  Require public key named NAME to sign. NAME can be any string up to 16 characters.
older(NUM) |  Require that the nSequence value is at least NUM. NUM cannot be 0.
and(POL,POL) |  Require that both subpolicies are satisfied.
or([N@]POL,[N@]POL) |  Require that one of the subpolicies is satisfied. The numbers N indicate the relative probability of each of the subexpressions (so 9@ is 9 times more likely than the default).
thresh(NUM,POL,POL,…) |  Require that NUM out of the following subpolicies are met (all combinations are assumed to be equally likely).
Table 2.7: Description of Miniscript policies extracted directly from the
Miniscript website [8].

###  2.3 Foundations of Security

Throughout this thesis we will rely on strategies and concepts derived from
the history of warfare and conflict. As many others have done before, these
concepts will be applied to the modern domain of information security. Let us
describe each of these concepts because they appear regularly throughout.

Defence-in-depth is an approach to system security wherein multiple layers of
controls are used to guard an asset. An attacker must exploit a vulnerability
in each control layer to reach their target. The redundancy of controls
increases the energy and time required from an attacker to be successful.
Often, this can give the defender an opportunity to react with reinforcements.
Defence-in-depth should be deployed across each system layer: people, process,
and technology. Ideally, the defender would set-up diverse controls that
require different kinds of expertise and or specialist equipment for an attack
sequence to be successful. Ideally, the defender would weaken the attacker as
the sequence progresses, by gathering information and where possible counter-
attacking. For example, by determining the attacker’s location and calling the
police.

Compartmentalisation is an approach to segregate critical information or
assets from one another by limiting access to them with, for example, role-
based policies, physical environments, or cryptographic keys. This strategy
helps a defender to limit the scope and damage of successful attacks.
Interactions between compartments should be limited for maximum effectiveness.
While defence-in-depth forces an attacker to complete a sequence of exploits,
compartmentalisation forces an attacker to complete multiple separate attack
sequences to compromise the system.

Choke points are used to force the attacker through a specific channel
controlled and monitored by the defender. Traditionally, a castle would be
constructed with high walls and a moat, with only a bridge and a gate readily
accessible. Together these act as a choke point, where intruders must pass
through the gate to enter. Defenders can inflict devastating damage while the
attacker passes through the choke point, or deter attacks from happening at
all due to their asymmetric advantage here. A firewall is an example of a
choke point in network security.

Least privilege is a design constraint that states that any agent (human,
machine or process) should only have access to the information or assets they
require in order to carry out their legitimate responsibilities, and only for
the minimum amount of time necessary. It is unnecessary to give more
privileges than required, and doing so increases the fragility of a system.
For example, an administrative intern does not need root access to the company
database to update employee attendance sheets, they merely need read and write
access for that sheet.

Weakest links are components within systems that have the most exploitable
vulnerabilities. By definition, a system is only as secure as its weakest
link. When reinforcing a system, add countermeasures to mitigate attacks on
the weakest components first.

Fail-secure components are crucial, particularly with complicated systems with
many components. If a component fails, the system should not permit insecure
behaviour. This is generally achieved by applying a deny-by-default policy and
not permitting any behaviour while the component is inactive. Using fail-
secure components may not always be possible if continuity and availability
are strict requirements.

###  2.4 Key-deletion

The successful enforcement of deleted-key covenants–the technical construct to
be introduced in chapter 4–is contingent upon the effectiveness of private key
deletion. Here we review this topic and explore the practical implications of
different approaches.

The secure erasure of data from a physical medium is a critical security
process in many contexts where the disclosure of privileged or confidential
information must be avoided. As defined in a survey of the state of knowledge
of secure data deletion [246]; ‘data is securely deleted from a system if an
adversary that is given some manner of access to the system is not able to
recover the deleted data from the system’. The techniques for securely
deleting data differ when using a magnetic hard drive or flash memory.
Moreover, the techniques differ when attempting to delete through interfaces
at different levels of the system; through a controller at the hardware layer,
through the file system at the operating system layer, and through software at
the user-interface layer. If the private key’s entire life-cycle can be
contained in volatile memory (RAM) alone, then its deletion will be dependent
on the physical properties of SRAM or DRAM cards. However, if the private key
is ever written to disk, its erasure will be dependent on the physical storage
medium being used too, typically it will be EEPROM or Flash storage.

Kissel et al. discuss guidlines for media sanitization in [174]. They define
four types of media sanitization which, in the following order, become more
thorough and resistant to information recovery; disposal, clearing, purging,
and destroying. Disposal here means simply discarding the storage media and is
very susceptible to information recovery. Clearing is a sanitization process
for which information cannot be re-gained using data, disk, or file recovery
utilities. Overwriting information with random data is an example of clearing.
Purging is a sanitization process that resists specialized laboratory attacks.
An example of purging from magnetic drives is to use a degausser, which
generates a strong magnetic field to remove the information contained in the
drive’s magnetic domains. Finally, destroying media is the most secure form of
media sanitization. This could be done by incinerating, shredding, melting or
pulverising the storage media. Factors such as cost must be considered along
with effectiveness when deciding which media sanitization processes are
suitable. In the context of an organization, the sanitization process should
be conducted on a significantly representative sample of storage media to
verify the process, ideally employing a non-biased expert entity to conduct
the verification.

Valamehr et al. [277] discuss physical inspection attacks for determining
information contained on storage devices, stating that there are two classes
of attacks; passive and intrusive. Passive attacks will probe the interface of
the device to discern timing or electrical differences. Active attacks will
breach the boundaries of the device to probe, scan and alter the device
internally. According to Valamehr et al. both EEPROM and Flash memory store
charge on a floating gate. When their memory cells are overwritten, some
residual information is retained as a bias on the substrate. This is the basis
for physical inspection attacks with an electron microscope. Similarly for
volatile memory, SRAM memory cells can retain some level of information and
are subject to similar analyses. Their work explores how to construct device
architectures that resist information leakage even when subjected to physical
inspection attacks.

Other work, which also relies on the imperfect nature of recovering data,
attempt to incorporate an additional layer of security by using key hiding
techniques based on leakage-resistant cryptography. Examples include exposure-
resilient functions and all-or-nothing transforms [83] and distributed public
key schemes secure against continual leakage [46]. This exemplifies only a
small portion of the work being done to improve physical inspection security
of devices, but also demonstrates that the current state-of-the-art fails to
handle the totality of the complexity of secure key deletion. These and
similar methods may prove useful in future if the theory and implementations
advance to support better performing systems and hardware device manufacturers
can integrate them into their products.

Other work focuses on provable deletion for embedded devices [235, 169, 146].
The ‘black box’ nature of secure deletion functions, which are often carried
out in Trusted Platform Modules (the standard, for example, of key-management
in the financial industry [52]) is unsatisfactory as it requires complete
trust in the correct implementation of software inside the module. Provable
deletion on the other hand is a scheme to enable users to verify the deletion
operations. The provable deletion schemes of [235, 169] work by requiring the
embedded device to compute a function on a data-set that fills its storage
capacity, and return the result as a proof that it stored that data-set which
necessitated overwriting all other data previously contained on the device.
These techniques may prove very useful for a hardware device manufacturer who
wishes to enable deleted-key covenant functionality.

Trusted erasable memory (using secure deletion tools and physical device
security measures) and disposable erasable memory (renders physical inspection
useless through destruction) differ in their security guarantees and cost
effectiveness. Even while using state-of-the-art in trusted erasable memory,
one can never be totally certain that no important confidential information
has been retained. However, the fact that these devices can be re-used
indefinitely for as many secure deletions as is desired makes them more
conducive to use in covenant-based applications. Disposable memory offers
maximally secure key deletion, but requiring a signing device to be destroyed
for each activation of a covenant is impractical. An example of how to
minimize wasted resources here would be to create batches of covenants on a
simple, cheap and ‘bare bones’ signing device such as a smart card, and to
destroy it, activating multiple covenants at a smaller cost than one per card.

No single method will ever enable perfect key deletion. However, the key
deletion process can be distributed across numerous heterogeneous devices
which rely on different methods. Each new device and deletion method acts as
an additional countermeasure that increases the cost for an attacker. Thus,
the security of key deletion can be enhanced by the set of enforcers and the
effort they put in to mitigate information recovery attacks. For an
enforcement policy of $m$-of-$n$, the key deletion process can resist up to
$n-m+1$ private keys being recovered. The trade-off is that more security
costs more money and time.

Thus it has been shown that there is a range of possible designs for secure
key deletion, each with a different security model and set of assumptions. If
security is paramount, then disposable (destructible) memory should be used.
However, if probabilistic security is sufficient, a distributed set-up of
trusted erasable memory devices may be used.

###  2.5 Protocols

####  2.5.1 Network Protocols

A network protocol is a formal set of rules, conventions and data structures
that governs how computers and other network devices exchange information over
a network. Kurose and Ross give the following definition [182]:

> “A protocol defines the format and the order of messages exchanged between
> two or more communicating entities, as well as the actions taken on the
> transmission and/or receipt of a message or other event.”

Some well-known network protocols include the Transmission Control Protocol
(TCP) [243], Internet Protocol (IP) [242], Hypertext Transfer Protocol (HTTP)
[120], and File Transfer Protocol (FTP) [244]. Network protocols are often
architected and implemented in a hierarchical manner, forming what is known as
the protocol stack. In this paradigm, each layer provides services to the
layer above it and relies on the services of the layer beneath it. This
layered approach allows for modularity, making design, implementation, and
testing more manageable. Higher-level protocols deal with abstract data and
system-level functions, whereas lower-level protocols handle more concrete
tasks such as data transmission and reception. Examples include the TCP/IP
model, which encapsulates protocols like IP, TCP, and HTTP in different
layers.

In this thesis, we focus on designing and analyzing new protocols that
leverage existing common internet protocols such as TCP/IP, as well as Bitcoin
network protocols. These new protocols aim to provide advanced transaction
functionalities in the Bitcoin ecosystem while maintaining compatibility with
the existing network infrastructure.

####  2.5.2 Ceremonies

A ceremony, as introduced by Ellison [113], is an extension of a network
protocol which broadens a system specification to include humans and their
interactions alongside networked devices. Humans and their actions are
considered ‘out-of-band’ to a network protocol, but not to a ceremony. Often,
failing to consider the human(s) operating a system can create security
vulnerabilities. Moreover, humans have capabilities that network devices do
not (e.g. strong authentication for someone they know) and can thus enable
otherwise ignored countermeasures that mitigate vulnerabilities [258].
However, humans also introduce complications. Humans have numerous weaknesses
including non-deterministic behaviour, memory limitations, bounded attention,
lack of knowledge of security, and so on. A taxonomy of human weaknesses was
presented by Carlos and Price [85]. They propose design recommendations to
minimise human-based vulnerabilities:

> 1\. Do not give users an unfeasible task.
> 2\. Prevent inappropriate interactions from being performed.
> 3\. Consider that the expected behaviour might change.
> 4\. Do not rely on user’s authentication capabilities (of digital objects or
> strangers).
> 5\. Integrate security into the main workflow (not as a secondary task).
>

For Bitcoin custody systems, humans are critical components. There is no
escaping human-mediated inputs when making payments. A custody system is owned
and managed by one or more humans and their decisions are essential to ongoing
operations.

####  2.5.3 Threat Model

A threat model serves as a structured and systematic blueprint that represents
an array of potential threats capable of compromising the security of a
system. This blueprint encapsulates diverse elements such as potential attack
vectors, profiles and capabilities of prospective attackers, as well as the
specific vulnerabilities these attackers could exploit.

When it comes to conducting a risk analysis for a ceremony, traditional threat
models designed for network protocols fall short. The evolution of threat
models has seen a progression from passive attacks, which merely eavesdrop on
communication channels, to active attacks, where messages are intercepted,
modified, replayed or otherwise manipulated. This notion of active attackers
was first considered by Needham and Schroeder [216] and later formalized by
Dolev and Yao [111]. The Dolev-Yao threat model has become the de-facto
standard for network protocol analysis [72]. To encapsulate the Dolev-Yao
model succinctly, it posits an attacker who controls all network traffic and
can perform any message operation, barring cryptanalysis. The underlying
assumption is that if a network protocol can withstand such a potent attacker,
it will remain secure against any realistically feasible attacker.

However, this model neither embodies realism nor sufficiency for a ceremony.
Certain communication channels are not strictly confined to a network. For
instance, a human $\leftrightarrow$ offline device channel might comprise of a
display and input buttons. A remote attacker, absent from the room, would not
have the ability to intercept this channel, rendering it unrealistic to assume
that an attacker can control that traffic and manipulate those messages.
Designing a ceremony to secure against an omnipotent, yet unrealistic,
attacker would necessitate additional countermeasures and complexities. This
could impose an undue burden on the user, potentially leading to erroneous
enactment of the ceremony. Consequently, an adaptive threat model was proposed
by Martina et al. for ceremony analysis [201]. They introduced a concise
notation to define an attacker’s capabilities for any given channel. We will
utilize the same notation as depicted in Table 2.8. A Dolev-Yao threat model
characterizes an attacker possessing all capabilities across all channels,
whereas a passive attacker threat model describes an attacker who can only
eavesdrop on channels.

| Capability | Meaning
---|---|---
E | Eavesdrop | Attacker can learn message contents
I | Initiate | Attacker can initiate messages with channel entities
A | Atomic Breakdown | Attacker can decompose messages into distinct data elements
C | Crypto | Attacker can perform cryptographic operations
B | Block | Attacker can block messages from being received
F | Fabricate | Attacker can fabricate messages
S | Spoof | Attacker can spoof the identity of one entity to the other
O | re-Order | Attacker can delay messages to a receiving entity and thus re-order them
Table 2.8: Summary of attacker capabilities for a ceremony threat model.

##  Chapter 3 Understanding Bitcoin Custody: Technologies, Systems, and Risk
Models

In this chapter we review the field of Bitcoin custody and introduce necessary
concepts and perspective in preparation for later chapters. We begin by
introducing terminology, motivating principles, and functional elements in
section 3.1. In section 3.2 we investigate the broad space of technology used
in custody systems, covering the theory and practice of key-management and
privacy in Bitcoin. Technological components form only a part of a custody
system. In addition, there are people and processes. We consider the
comprehensive view which integrates technology, people and processes in
section 3.3. Finally, in section 3.4, we consider how to model risk, and
review examples in the field. This chapter addresses thesis objective O1 (see
1.2).

###  3.1 Introduction to Bitcoin Custody

Bitcoin custody, put simply, is the act of holding and controlling bitcoin. A
custody system is comprised of technologies, processes, and people. The ideal
system would be safe (preventing failure) and secure (preventing attack). Of
course, an ideal system is not realistic. In designing Bitcoin custody systems
we can strive for safety and security by building tolerance to failure and
attack and by designing methods to recover from partial failure and
compromise.

Custody systems are the foundation of all applications and uses of Bitcoin.
Custody systems can be very simple or complex. Let us elaborate on types,
design principles, phases, and functions to build an intuition about custody
systems.

####  3.1.1 Types

A custody system can be controlled by one or more people. The custody system
may also be operated by some people on behalf of others who are the legal
owners of the bitcoin contained in the system. We say that a custody system is
autonomous if it is controlled and legally owned by the same entities. An
autonomous custody system is self-governing. Autonomous is often referred to
as self-custody or sovereign in the literature and industry. The ability for
anyone to use autonomous custody systems in Bitcoin is a critical difference
from state-backed fiat monetary systems, which are typically controlled by
privileged entities (banks and payment network operators). Autonomous custody
systems cannot be censored from receiving and sending bitcoin. The catch is
that autonomous custody systems come with responsibility to actively maintain
safety and security. We will call a custody system that is not autonomous a
heteronomous custody system. An example is a trust or an exchange. The same
processes and technologies can be used for both types of system. The existence
of autonomous custody systems for bitcoin are crucial to maintain the property
of censorship-resistance. Heteronomous custody systems inherently give another
entity power to prevent the user from making transactions, i.e. to censor the
user.

Another distinction to make is about single-party and multi-party custody
systems. A single-party custody system is completely controlled by one person.
That one person has full access to the system except in situations of failure
or attack. In multi-party custody systems, multiple people participate in
controlling how bitcoin is spent. Access policies can enforce dual control
(e.g. person A and person B), joint control (e.g. person A or person B), or
can enforce arbitrary control hierarchies with separation of duties. An
example is a large company where the finance team and compliance team both
need to authorise expenses requested from different product teams.

Custody systems can have components or functions which are outsourced to a
third-party. Examples include a fiduciary co-signer for payments or a
fiduciary recovery assistant in situations of failure or compromise. A third-
party could assist with data-availability for a custody system, or with
reliable access to the Bitcoin network, or could provide price information
about bitcoin.

Finally, let us describe the often-used jargon cold versus hot storage. Cold
storage refers to keeping private keys on offline devices or media. Cold
storage can include a purpose-built hardware device (e.g. a hardware security
module), paper, engraved metal, or even human memory. This minimises network-
based attacks at the expense of making the keys less available, requiring
manual action from the user to access the bitcoin. Hot storage refers to
keeping private keys on networked devices. While being online significantly
amplifies the potential attack surface, it simultaneously enhances the
availability of the bitcoin, thus facilitating easier access. It is
particularly useful for automated processes.

####  3.1.2 Design Principles

Using design principles is important to guide the development of custody
systems. It helps in setting objectives and defining system constraints.
Moreover, it helps by communicating to users the intent of system architects,
so that users can evaluate if the system is suitable for them.

An example set of design principles are given by a custody services company
called Casa in their ‘wealth security protocol’ [33]. Let us paraphrase them
here.

> Minimal knowledge. Users should disclose minimal information to others,
> including trusted counter-parties and other third-parties.
> High security. There should be no single point of compromise. Use defense-
> in-depth to increase the difficulty for attackers to compromise the custody
> system.
> Usability is security. Poor usability can create vulnerabilities. Poor
> usability will result in nobody using the custody system.
> Expert support. Users are generally not security experts. A custody system
> can make use of expert support to serve a wider range of users, to integrate
> feedback and develop better systems.
> Redundancy. There should be no single point of failure. A custody system can
> be resilient despite failure of some of its components.
> Sovereignty. Bitcoin was designed to give users autonomy. Heteronomous
> custody systems require trusting others, which creates vulnerabilities.
> Incentive alignment. Creating an alignment of commercial incentives with the
> success of the custody system will result in better development of the
> custody system.
> Bitcoin First. Bitcoin is the most secure and valuable digital currency. The
> same custody systems that are used for Bitcoin could eventually be used for
> other digital assets.

Blockchain Commons, a not-for-profit benefit corporation working with
developer communities in the area of digital assets and digital identity [2]
proposed similar design principles. Their stated goal is to “put the user
first and enable responsible key-management”. They have designed and built a
custody system called Gordian. Below, the Gordian principles are quoted;

> “Independence. Gordian improves user freedom from involuntary oversight or
> external control.
> Privacy. Gordian protects against coercion with non-correlation, privacy,
> and pseudonymity.
> Resilience. Gordian protects users to decrease the likelihood of them losing
> their funds via any means.
> Openness. Gordian supports open infrastructure that allows developers to
> create their own applications.”

Keep these principles in mind to understand why, sometimes, Bitcoin custody
systems are designed with an abundance of cryptographic, hardware, and
physical controls. They help to explain why, often, Bitcoin custody systems
are inconvenient for users in comparison to the simple mobile applications
used in retail banking.

####  3.1.3 Phases

Let us define three phases for a Bitcoin custody system. In the setup phase
the components of the custody system are initialised and the physical
environments that store components are prepared. If there are third-party
service providers, some data exchange may be required to initialise their
system too. The setup phase will consist of generating keys that will control
bitcoin, preparing key-storage devices, preparing device storage locations,
preparing other computation devices, and testing the entire system. Once the
setup phase is complete, the operation phase can begin. This includes
receiving and sending bitcoin payments, and checking the balance and health of
the system. If the system experiences partial failure or suffers an attack,
the recovery phase is designed to replace components and consolidate the
system. Recovery will often involve key backups and a transition of control to
newly generated keys controlled by remaining and new components.

####  3.1.4 Functions

Custody systems are comprised of components that perform one or more of
several common functions. Let us summarise these now.

Bitcoin private keys are 256-bit random numbers and are a fundamental data
type for custody systems. True randomness is required to generate private keys
securely. Many key-storage devices come with a built-in ‘true random number
generator’. Many devices also allow the user to enter random data, or
‘entropy’, manually. The user can roll dice to generate true random numbers.
The common function is private key generation.

Private keys are often stored on digital hardware; either general purpose
(e.g. a mobile or laptop), or purpose-built (e.g. a hardware security module).
To improve the resilience of a custody system against loss of private keys,
they are often backed up on analogue media. Examples include engraved metal
and archival paper. Lopp has a detailed study of different types of analogue
backup media [193, 194]. When using analogue media, the private key will often
be encoded as a human-friendly mnemonic seed, usually 24 words, as specified
in BIP-39 [231]. The common function is private key storage.

To operate the custody system, private keys must be accessed and used to sign
transactions. This function requires computation, and many purpose-built
signing devices exist [7]. General purpose devices can function as a signing
device too. The common function is signing.

Bitcoin payments are encoded as transactions. Transactions define how control
of bitcoin transfers from one entity to another. Transaction messages are
authorised with signatures generated using private keys. A transaction
coordinator is a device (often general purpose) that can create transactions
and share them with signing devices.

The counterpart to signature generation is signature verification. Typically,
signing devices and transaction coordinators will be equipped with this
functionality.

Another common function is a Bitcoin network server. This is a server running
Bitcoin software to be a peer in the peer-to-peer network. This function
consists of downloading new blocks of transactions, verifying blocks and
transactions, and coordinating the broadcast of transactions.

As previously noted, the current state of bitcoin is encapsulated by the set
of unspent transaction outputs, also referred to as coins. Similarly, the
state of a custody system is the set of coins which it controls. The total
balance is the sum of available coins. Knowing which coins exist requires a
Bitcoin network server. Knowing which coins are in control of the system
requires knowledge of private key storage (though not necessarily direct
knowledge of the private key). The common function is state tracking (the
custody system state).

The term wallet is often used to describe software that can perform one or
several of these common functions. It is an ambiguous term. Sometimes it is
used to refer to a complete custody system. Sometimes it is used to refer to a
set of keys controlled by the user. Sometimes it is used to describe a key-
storage and signing device. We will avoid any confusion by not using this term
except with an explicit description of the functions supported or in reference
to other work that uses it. The term is particularly unhelpful for modular
custody systems which partition functionality across separate components.

###  3.2 Technology Primer

There is a broad array of technologies that can be used in custody systems to
achieve security, safety, usability, and privacy. Herein we will present the
concepts, discuss their utility, and refer to noteworthy research.

Technology can be used to create custody systems based on a user-friendly yet
resilient key-management strategy coupled with a privacy framework. The former
relates to control of bitcoin, while the latter relates to what information is
revealed as assets and technologies are used. Moreover, the two are inter-
related; maintaining privacy helps to reduce the risk associated with
compromised keys, and conversely, key-management techniques may reveal
operational information to external observers. Financial privacy may be
paramount for success in business, and is critical for the safety of users
with significant holdings.

####  3.2.1 Key-management in Theory

##### Security Objectives

Each key has a life-cycle. First, a key is generated. Then, it has a period
wherein it is used to perform cryptography tasks. Then it is decommissioned
(no longer used). Finally, it may be deleted. The user must control the key
for its entire life-cycle.

Key-management is a long-standing issue for the usability of cryptography
schemes. For an autonomous custody system, users are in control of their own
bitcoin and have no possibility for recourse in the event of loss or theft,
therefore, methods for dealing with various failure modes in key-management
are necessary. Au et al. used actuarial techniques to estimate that, by June
2020, $7.3 billion worth of bitcoin had been lost since the system launched in
2009 [60].

In Bitcoin, coins are specified as unspent transaction outputs (UTXOs) and are
publicly linked to addresses. In the simplest case, an address is generated by
taking the hash of the relevant public key111Addresses may also represent more
complex associations between UTXOs and, for example, multiple public keys.. In
order to move coins, a transaction message (which meets the validation
criteria of consensus rules) must be signed with the private key that
corresponds to the address (public key) linked to those coins and be broadcast
to the network.

Thus, confidentiality of the private key is a critical security objective. If
a person or machine successfully learns the private key, they will be able to
use it to sign transactions to move any bitcoin from the address associated
with that private key to any other address.

Confidentiality is also important for public keys, in order to maintain
privacy. Achieving this while interacting with a public ledger of records can
be challenging. Re-using public keys can result in several transactions being
identified as from the same user. Observers can simply match addresses across
different transactions. An address (derived from one or more public keys) is a
pseudonym for a user. The use of pseudonyms in Bitcoin enables optional audit-
ability. In some cases, it may be desirable to hold and transact bitcoin in a
publicly verifiable way. In other cases, it may be desirable to remain
anonymous.

A custody system ought to be designed to support the user’s expected usage
behaviour. The security objective here is to enable sufficient availability
for private and public keys to enable their use. Some users may need low
frequency and irregular access to their private keys, while others may require
continual access. With the public key, the user can check their balance and
create an address to receive payments. We may expect higher availability
requirements for public keys.

Integrity of one’s private and public keys is an important security objective.
A user may demonstrate the integrity of their private key by using it to sign
a message or a test transaction. The user must take care to ensure the
integrity of their public key when sharing an address (derived from the public
key) with their counter-party in order to receive a payment. Together, a valid
signature on a message and a public key can be used to demonstrate to a third-
party that one controls bitcoin; this is referred to as proof-of-reserves
[272].

##### Key-trees

Bitcoin keys are typically generated as a deterministic wallet (in this case,
‘wallet’ is referring to a collection of keys). A deterministic wallet starts
with a mnemonic seed phrase, as standardised with BIP-39 [231]. From this, a
key derivation function is used to produce a master key-pair and subsequently
to produce a chain of descendant key-pairs. Most wallets adhere to the
standard introduced in 2012, BIP-32 [290], referred to as hierarchical
deterministic (HD) wallets in which an initial mnemonic seed phrase is used to
derive a tree of (public key, private key) pairs.

We will refer to HD wallets as key-trees. A key-tree simplifies the management
of using many keys. If designed well, a key-tree can enhance privacy, improve
coordination among devices and regular counter-parties, optimise storage of
large key-sets, and simplify the backup of keys. Now we consider how a key-
tree is constructed.

Recall that one of the inputs to a key derivation function is a random number.
In BIP-32 both public and private keys, $(k,K)$, are appended with a random
number $c$. This is an extra 256-bit string referred to as the chaincode which
is an argument in the key derivation function. Together, the key and chaincode
are called an extended key. A private and public key-pair share the same
chaincode, such that the extended private key is $(k,c)$ and the extended
public key is $(K,c)$.

There is a key derivation function to go from;

> parent private key $\rightarrow$ child private key,
> parent private key $\rightarrow$ child public key, and
> parent public key $\rightarrow$ child public key.

Deriving a private key from a public key is not possible because of the ECDLP.
Deriving a parent key from a child key is not possible because the key
derivation function is one-way.

A derivation index is included as an argument in the key derivation function
and is used to separate key-chains as branches in the key-tree. Each extended
key-pair can be the root of a sub-tree with its own derived branches.

There are two types of derivation; hardened and non-hardened. Hardened
derivation includes the private key as an argument in the key derivation
function (whether the parent key is private or public). One can’t compute a
hardened child key without knowledge of the parent private key. Conversely,
non-hardened derivation includes the public key as an argument in the key
derivation function. Non-hardened derivation doesn’t require knowledge of the
private key.

As a consequence, knowing an extended private key is sufficient to compute a
complete chain of descendant private and public keys. Whereas knowing an
extended public key is sufficient to compute all descendant non-hardened
public keys.

It is useful to share an extended public key with a regular counter-party.
This way, they may derive a fresh public key each time they make a payment to
you without any interaction. Note, however, that given a hardened extended
public key, $(K_{1},c_{1})$, and any extended private key in the descendent
chain, $(k_{i},c_{i})$, it’s possible to compute the hardened extended private
key $(k_{1},c_{1})$ [82]. Generally, one must assume that a compromised
hardened extended private key results in a compromised sub-tree.

Observe that the user can backup their entire key-tree with a single mnemonic
phrase. Similarly, a signing device may optimise storage by only storing the
master extended key-pair, the derivation index, and the current chain depth
instead of the entire key-tree.

Das et al. presented a formal model for BIP-32 HD wallet systems and
demonstrated precisely the security properties it achieves [97]. Several other
works have proposed variations of the standard with slight improvements or
additional functionality [145, 197, 117, 140].

##### Pseudonymity

The motivation for using fresh public keys with each payment is to maintain
privacy. Recall that a public key is a pseudonym for the user. Once a
pseudonym is linked to a real identity, we consider the privacy to be broken.

> Privacy objective 1. Avoid creating links between real identities and
> pseudonyms.

This could mean avoiding ‘Know Your Customer’ regulated transactions,
protecting the IP when broadcasting transactions to the network, or not giving
away geo-location data when interacting with Bitcoin applications and
services. It should be obvious too that sharing information about public keys
and addresses with people (family, friends or colleagues) or online sites
(forums or exchanges) compromises privacy.

Unfortunately, transacting in bitcoin for goods or services creates a scenario
where the seller and buyer must reveal a pseudonym to each other. Revelation
of pseudonyms will always be a risk.

> Privacy objective 2. Manage a diverse set of un-linked pseudonyms.

Compartmentalising bitcoin across multiple pseudonyms (as UTXOs with different
addresses) is a risk-management strategy that mitigates the impact of
accidental or forced identity leaks through de-anonymization methods.

Key-trees enable users to avoid re-using public keys and enhance privacy. They
help users maintain maximal un-linkability of their pseudonyms. If privacy is
paramount, then hardened key derivation can be used. A hardened descendant
key-pair can only be computed with access to the parent private key. Provided
that the private key is not compromised, it is not feasible for an attacker to
derive the chain of public keys even if any individual public keys are
revealed.

##### Transaction graph analysis

Methods to cluster ownership of UTXOs are not only based on the public keys
used to derive addresses, but also on the structure of connected transactions.

An UTXO created with a prior transaction becomes a spent input for a new
transaction. A single transaction may contain several inputs and outputs. It
is even possible to aggregate inputs from various signatories in the same
transaction and to distribute new outputs among addresses controlled by
different recipients.

This way, transactions are linked. We can represent this as a transaction
graph. This graph can be derived from the public blockchain data structure to
analyse which addresses are likely associated with the same custody system,
service, or person. When a UTXO is spent it is totally consumed by the
transaction; any excess value that is not intended for the recipient must be
used to create a change output with an address controlled by the sender. It is
advisable to generate fresh change addresses with each transaction, to adhere
to the objective of maintaining a diverse set of un-linked pseudonyms.

Following this method eventually leads to a situation where the total value of
funds is thinly distributed across many addresses in small amounts. If there
is not enough value in any individual unspent output for some intended
transaction, then these change outputs must be aggregated to form a new UTXO
with sufficient value. Doing this creates a public correlation between the
change outputs and the transactions that created them.

> Privacy objective 3.  Minimise cross-transaction correlation.

We will consider privacy services that can obfuscate transaction graph
analyses in section 3.2.5.

##### Access control

A seed (or the master private key) is a single point of compromise for a
custody system using a single key-tree. For single-party and multi-party
custody systems, researchers and practitioners have instead turned to using
systems with keys (or key-shares) distributed across hardware devices,
locations, software and people. This is how to build defence-in-depth and how
to avoid weak links at the key-management layer.

With multiple keys and key usage controls (cryptography and physical),
arbitrary access control structures can be defined which determine who or what
devices can authorise sending and receiving payments.

When keys are contained to distinct devices or media, they can be stored in
distinct physical locations. Each location will have its own physical controls
that define the physical security environment; safe, combination lock, alarm,
cameras, security guards, etcetera. The design of physical security
environments is beyond the scope of this thesis. It is common for home owners
and organisations to implement physical controls to safeguard their assets.
Each control forms part of the access control structure.

The access control structure is also determined through cryptography and
Bitcoin engineering. The general approach is to use a multi-signature scheme.