Skip to content

Commit 442a4f1

Browse files
committed
Initial commit
0 parents  commit 442a4f1

6 files changed

Lines changed: 1496 additions & 0 deletions

File tree

.github/workflows/ci.yaml

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches: [main]
6+
pull_request:
7+
branches: [main]
8+
9+
env:
10+
RUSTFLAGS: --deny warnings
11+
12+
jobs:
13+
lint:
14+
runs-on: ubuntu-latest
15+
steps:
16+
- uses: actions/checkout@v4
17+
18+
- name: Install Rust
19+
uses: dtolnay/rust-toolchain@stable
20+
with:
21+
components: clippy, rustfmt
22+
23+
- uses: Swatinem/rust-cache@v2
24+
25+
- name: Clippy (default features)
26+
run: cargo clippy --all-targets
27+
28+
- name: Clippy (all features)
29+
run: cargo clippy --all-targets --all-features
30+
31+
- name: Format
32+
run: cargo fmt --all -- --check
33+
34+
test:
35+
name: Test on ${{ matrix.os }}
36+
runs-on: ${{ matrix.os }}
37+
strategy:
38+
fail-fast: false
39+
matrix:
40+
os: [ubuntu-latest, windows-latest, macOS-latest]
41+
42+
steps:
43+
- uses: actions/checkout@v4
44+
45+
- name: Install Rust
46+
uses: dtolnay/rust-toolchain@stable
47+
48+
- uses: Swatinem/rust-cache@v2
49+
50+
- name: Test default features
51+
run: cargo test
52+
53+
- name: Test all features
54+
run: cargo test --all-features

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/target
2+
Cargo.lock

Cargo.toml

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
[package]
2+
name = "confidential-script-lib"
3+
version = "0.1.0"
4+
description = "Authorize on-chain transactions with off-chain verification of Bitcoin script"
5+
keywords = [ "bitcoin", "script", "kernel", "emulation", "tee" ]
6+
authors = ["Joshua Doman <joshsdoman@gmail.com>"]
7+
license = "CC0-1.0"
8+
homepage = "https://github.com/joshdoman/confidential-script-lib"
9+
repository = "https://github.com/joshdoman/confidential-script-lib"
10+
edition = "2024"
11+
readme = "README.md"
12+
rust-version = "1.85.0"
13+
14+
[features]
15+
default = ["std"]
16+
std = ["bitcoin/std"]
17+
bitcoinkernel = ["dep:bitcoinkernel"]
18+
compiler = []
19+
trace = []
20+
21+
[dependencies]
22+
bitcoin = "0.32.5"
23+
bitcoin-units = "0.1.2"
24+
bitcoinkernel = { version = "0.0.22", optional = true }
25+
hmac = "0.12.1"
26+
num-bigint = "0.4.6"
27+
sha2 = "0.10.9"
28+
29+
[dev-dependencies]
30+
bitcoinkernel = "0.0.22"

LICENSE.txt

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
Creative Commons Legal Code
2+
3+
CC0 1.0 Universal
4+
5+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12+
HEREUNDER.
13+
14+
Statement of Purpose
15+
16+
The laws of most jurisdictions throughout the world automatically confer
17+
exclusive Copyright and Related Rights (defined below) upon the creator
18+
and subsequent owner(s) (each and all, an "owner") of an original work of
19+
authorship and/or a database (each, a "Work").
20+
21+
Certain owners wish to permanently relinquish those rights to a Work for
22+
the purpose of contributing to a commons of creative, cultural and
23+
scientific works ("Commons") that the public can reliably and without fear
24+
of later claims of infringement build upon, modify, incorporate in other
25+
works, reuse and redistribute as freely as possible in any form whatsoever
26+
and for any purposes, including without limitation commercial purposes.
27+
These owners may contribute to the Commons to promote the ideal of a free
28+
culture and the further production of creative, cultural and scientific
29+
works, or to gain reputation or greater distribution for their Work in
30+
part through the use and efforts of others.
31+
32+
For these and/or other purposes and motivations, and without any
33+
expectation of additional consideration or compensation, the person
34+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35+
is an owner of Copyright and Related Rights in the Work, voluntarily
36+
elects to apply CC0 to the Work and publicly distribute the Work under its
37+
terms, with knowledge of his or her Copyright and Related Rights in the
38+
Work and the meaning and intended legal effect of CC0 on those rights.
39+
40+
1. Copyright and Related Rights. A Work made available under CC0 may be
41+
protected by copyright and related or neighboring rights ("Copyright and
42+
Related Rights"). Copyright and Related Rights include, but are not
43+
limited to, the following:
44+
45+
i. the right to reproduce, adapt, distribute, perform, display,
46+
communicate, and translate a Work;
47+
ii. moral rights retained by the original author(s) and/or performer(s);
48+
iii. publicity and privacy rights pertaining to a person's image or
49+
likeness depicted in a Work;
50+
iv. rights protecting against unfair competition in regards to a Work,
51+
subject to the limitations in paragraph 4(a), below;
52+
v. rights protecting the extraction, dissemination, use and reuse of data
53+
in a Work;
54+
vi. database rights (such as those arising under Directive 96/9/EC of the
55+
European Parliament and of the Council of 11 March 1996 on the legal
56+
protection of databases, and under any national implementation
57+
thereof, including any amended or successor version of such
58+
directive); and
59+
vii. other similar, equivalent or corresponding rights throughout the
60+
world based on applicable law or treaty, and any national
61+
implementations thereof.
62+
63+
2. Waiver. To the greatest extent permitted by, but not in contravention
64+
of, applicable law, Affirmer hereby overtly, fully, permanently,
65+
irrevocably and unconditionally waives, abandons, and surrenders all of
66+
Affirmer's Copyright and Related Rights and associated claims and causes
67+
of action, whether now known or unknown (including existing as well as
68+
future claims and causes of action), in the Work (i) in all territories
69+
worldwide, (ii) for the maximum duration provided by applicable law or
70+
treaty (including future time extensions), (iii) in any current or future
71+
medium and for any number of copies, and (iv) for any purpose whatsoever,
72+
including without limitation commercial, advertising or promotional
73+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74+
member of the public at large and to the detriment of Affirmer's heirs and
75+
successors, fully intending that such Waiver shall not be subject to
76+
revocation, rescission, cancellation, termination, or any other legal or
77+
equitable action to disrupt the quiet enjoyment of the Work by the public
78+
as contemplated by Affirmer's express Statement of Purpose.
79+
80+
3. Public License Fallback. Should any part of the Waiver for any reason
81+
be judged legally invalid or ineffective under applicable law, then the
82+
Waiver shall be preserved to the maximum extent permitted taking into
83+
account Affirmer's express Statement of Purpose. In addition, to the
84+
extent the Waiver is so judged Affirmer hereby grants to each affected
85+
person a royalty-free, non transferable, non sublicensable, non exclusive,
86+
irrevocable and unconditional license to exercise Affirmer's Copyright and
87+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
88+
maximum duration provided by applicable law or treaty (including future
89+
time extensions), (iii) in any current or future medium and for any number
90+
of copies, and (iv) for any purpose whatsoever, including without
91+
limitation commercial, advertising or promotional purposes (the
92+
"License"). The License shall be deemed effective as of the date CC0 was
93+
applied by Affirmer to the Work. Should any part of the License for any
94+
reason be judged legally invalid or ineffective under applicable law, such
95+
partial invalidity or ineffectiveness shall not invalidate the remainder
96+
of the License, and in such case Affirmer hereby affirms that he or she
97+
will not (i) exercise any of his or her remaining Copyright and Related
98+
Rights in the Work or (ii) assert any associated claims and causes of
99+
action with respect to the Work, in either case contrary to Affirmer's
100+
express Statement of Purpose.
101+
102+
4. Limitations and Disclaimers.
103+
104+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
105+
surrendered, licensed or otherwise affected by this document.
106+
b. Affirmer offers the Work as-is and makes no representations or
107+
warranties of any kind concerning the Work, express, implied,
108+
statutory or otherwise, including without limitation warranties of
109+
title, merchantability, fitness for a particular purpose, non
110+
infringement, or the absence of latent or other defects, accuracy, or
111+
the present or absence of errors, whether or not discoverable, all to
112+
the greatest extent permissible under applicable law.
113+
c. Affirmer disclaims responsibility for clearing rights of other persons
114+
that may apply to the Work or any use thereof, including without
115+
limitation any person's Copyright and Related Rights in the Work.
116+
Further, Affirmer disclaims responsibility for obtaining any necessary
117+
consents, permissions or other rights required for any use of the
118+
Work.
119+
d. Affirmer understands and acknowledges that Creative Commons is not a
120+
party to this document and has no duty or obligation with respect to
121+
this CC0 or use of the Work.

README.md

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# confidential-script-lib
2+
3+
`confidential-script-lib` is a Rust library for emulating Bitcoin script within a Trusted Execution Environment (TEE), such as an AWS Nitro Enclave. It enables the off-chain execution of complex script, by validating unlocking conditions inside a secure environment and then authorizing the transaction using a deterministically derived private key.
4+
5+
This approach allows for confidential execution of complex script, including opcodes not yet supported by the Bitcoin protocol. The actual on-chain footprint is a minimal key-path spend, preserving privacy and efficiency.
6+
7+
## Overview
8+
9+
The library operates on a two-step process: emulation and signing.
10+
11+
1. **Emulation**: A transaction is constructed using an input spending a *real* `previous_outpoint` with a witness that is a script-path spend from an *emulated* P2TR `script_pubkey`. This library validates this emulated witness using a `Verifier`, which closely matches the API of `rust-bitcoinkernel`. Using the `bitcoinkernel` feature, users can use this default verifier, or they can provide an alternative verifier that enforces a different set of rules (ex: a fork of `bitcoinkernel` that supports Simplicity).
12+
13+
2. **Signing**: If verified, the library uses the provided parent private key and the merkle root of the *emulated* script path spend to derive a child private key, which corresponds to the internal public key of the *actual* UTXO being spent. The library then updates the transaction with a key-path spend using this child key.
14+
15+
To facilitate offline generation of the real `script_pubkey`, the child key is derived from the parent key using a non-hardened HMAC-SHA512 derivation scheme. This lets users generate addresses using the parent public key, while keeping the parent private key secure.
16+
17+
This library is intended to be run within a TEE, which is securely provisioned with the parent private key. This decouples script execution from on-chain settlemnt, keeping execution private and enabling new functionality with minimal trust assumptions.
18+
19+
## Failsafe Mechanism: Backup Script Path
20+
21+
To prevent funds from being irrecoverably locked if the TEE becomes unavailable, the library allows for the inclusion of an optional `backup_merkle_root` when creating the actual on-chain address. This backup root defines alternative spending paths that are independent of the TEE.
22+
23+
A common use case for this feature is to include a timelocked recovery script (e.g., using `OP_CHECKSEQUENCEVERIFY`). If the primary TEE-based execution path becomes unavailable for any reason, the owner can wait for the timelock to expire and then recover the funds using a pre-defined backup script. This provides a crucial failsafe, ensuring that users retain ultimate control over their assets.
24+
25+
## Extensibility for Proposed Soft Forks
26+
27+
This library can be used to emulate proposed upgrades, such as new opcodes like `OP_CAT` or `OP_CTV` or new scripting languages like Simplicity. It accepts any verifier that adheres to the `rust-bitcoinkernel` API, allowing developers to experiment with new functionality by forking the kernel, without waiting for a soft fork to gain adoption on mainnet.
28+
29+
## Recommended Setup
30+
31+
This library is intended to be used within a Nitro Enclave, integrated with KMS such that any AWS account can provision an identical enclave with the same master private key. For maximum security, the KMS key should be created with a policy making it non-deletable and only accessible to enclaves running a specific image. The policy should also be irrevocable, ensuring the key cannot be used outside the enclave in the future.
32+
33+
To generate the master secret, an enclave should generate a random secret and use `GenerateDataKey` to encrypt it using KMS. To provision a different enclave with the secret, the user should provide the enclave the encrypted data key and the encrypted secret, which the enclave can then decrypt with KMS using `Decrypt`.
34+
35+
Finally, the enclave should be able to expose the master public key, so that users can independently derive the on-chain address they should send funds to.
36+
37+
## Usage
38+
39+
### Verifier
40+
41+
```rust
42+
/// Trait to abstract the behavior of the bitcoin script verifier, allowing
43+
/// users to provide their own verifier.
44+
pub trait Verifier {
45+
/// Verify a bitcoin script, mirroring the API of `bitcoinkernel::verify`.
46+
///
47+
/// # Arguments
48+
/// * `script_pubkey` - The script public key to verify.
49+
/// * `amount` - The amount of the input being spent.
50+
/// * `tx_to` - The transaction containing the script.
51+
/// * `input_index` - The index of the input to verify.
52+
/// * `flags` - Script verification flags.
53+
/// * `spent_outputs` - The outputs being spent by the transaction.
54+
///
55+
/// # Errors
56+
/// Returns `KernelError` if verification fails.
57+
fn verify(
58+
&self,
59+
script_pubkey: &[u8],
60+
amount: Option<i64>,
61+
tx_to: &[u8],
62+
input_index: u32,
63+
flags: Option<u32>,
64+
spent_outputs: &[TxOut],
65+
) -> Result<(), Error>;
66+
}
67+
68+
/// The default `Verifier` implementation that uses `bitcoinkernel`.
69+
pub struct DefaultVerifier;
70+
```
71+
72+
### Convert emulated transaction
73+
74+
```rust
75+
/// Verifies an emulated Bitcoin script and signs the corresponding transaction.
76+
///
77+
/// This function performs script verification using bitcoinkernel, verifying an
78+
/// emulated P2TR input. If successful, it derives an XOnlyPublicKey from the
79+
/// parent key and the emulated merkle root, which is then tweaked with an optional
80+
/// backup merkle root to derive the actual spent UTXO, which is then key path signed
81+
/// with `SIGHASH_DEFAULT`.
82+
///
83+
/// # Arguments
84+
/// * `verifier` - The verifier to use for script validation
85+
/// * `emulated_script_pubkey` - The P2TR script to verify against
86+
/// * `amount` - The amount for the input
87+
/// * `emulated_tx_to` - Serialized transaction to verify and sign
88+
/// * `input_index` - Index of the input to verify and sign (0-based)
89+
/// * `emulated_spent_outputs` - Outputs being spent in the emulated transaction
90+
/// * `actual_spent_outputs` - Actual outputs for signature generation
91+
/// * `aux_rand` - Auxiliary random data for signing
92+
/// * `parent_key` - Parent secret key used to derive child key for signing
93+
/// * `backup_merkle_root` - Optional merkle root for backup script path spending
94+
///
95+
/// # Errors
96+
/// Returns error if verification fails, key derivation fails, or signing fails
97+
pub fn verify_and_sign<V: Verifier>(
98+
verifier: &V,
99+
emulated_script_pubkey: &[u8],
100+
amount: i64,
101+
emulated_tx_to: &[u8],
102+
input_index: u32,
103+
emulated_spent_outputs: &[TxOut],
104+
actual_spent_outputs: &[TxOut],
105+
aux_rand: &[u8; 32],
106+
parent_key: SecretKey,
107+
backup_merkle_root: Option<TapNodeHash>,
108+
) -> Result<Transaction, Error>;
109+
```
110+
111+
### Generate an address
112+
113+
```rust
114+
/// Generates P2TR address from a parent public key and the emulated merkle root,
115+
/// with an optional backup merkle root.
116+
///
117+
/// # Arguments
118+
/// * `parent_key` - The parent public key
119+
/// * `emulated_merkle_root` - The merkle root of the emulated input
120+
/// * `backup_merkle_root` - Optional merkle root for backup script path spending
121+
/// * `network` - The network to generate the address for
122+
///
123+
/// # Errors
124+
/// Returns an error if key derivation fails
125+
fn generate_address(
126+
parent_key: PublicKey,
127+
emulated_merkle_root: TapNodeHash,
128+
backup_merkle_root: Option<TapNodeHash>,
129+
network: Network,
130+
) -> Result<Address, secp256k1::Error>;
131+
```
132+
133+
## Testing
134+
The default `Verifier` implementation is based on `bitcoinkernel`, which is an optional feature but required to run the included tests.
135+
136+
Use the following command to run the test suite:
137+
138+
```bash
139+
cargo test --features bitcoinkernel
140+
```
141+
142+
Or run:
143+
144+
```bash
145+
cargo test --all-features
146+
```
147+
148+
## License
149+
150+
This project is licensed under the CC0-1.0 License.
151+
152+
## Author
153+
154+
Joshua Doman <joshsdoman@gmail.com>

0 commit comments

Comments
 (0)