Any compilation environment where the type of the operations
value is
irrelevant.
A properly-formed instruction used by an AuthenticationVirtualMachine
.
Allowable identifiers for authentication virtual machine versions. The BCH
prefix identifies the Bitcoin Cash network, the BSV
prefix identifies the
Bitcoin SV network, and the BTC
prefix identifies the Bitcoin (Core)
network.
Virtual machine versions may be marked with the SPEC
suffix to indicate
that they have not yet been deployed to a main network and are therefore only
a draft specification. After deployment, when template compatibility is
verified, templates should update their supported
array to indicate
compatibility with the live virtual machine version.
The available networks for common Base58Address versions.
A successfully generated lockingBytecode
(for an output) or
unlockingBytecode
(for an input). Because this bytecode generation was
successful, the associated compilation directive in the transaction template
can be replaced with this result for subsequent compilations. For example, if
most inputs were successfully compiled, but some inputs require keys held by
another entity, the transaction template can be updated such that only the
final inputs contain compilation directives.
A compiler operation method which accepts the identifier being evaluated, the
compilation data, and the compilation environment, and returns a
CompilerOperationResult
.
the type of the TransactionContext
in
CompilationData<TransactionContext>
expected by this operation
if true, this operation may return
CompilerOperationSkip
to indicate that it cannot be applied and should be
skipped
the type of the CompilationData
expected by this
operation
the type of the CompilationEnvironment
expected by
this operation
An unsuccessful compiler operation result.
A successful compiler operation result.
A successful signature-generation compiler operation. This provides slightly
more debugging information than CompilerOperationSuccessGeneric
. The
signing serialization or data message which was hashed to produce the
to-be-signed message is also provided in the result.
Valid identifiers describing the various full and partial signing serializations available to the compiler.
Valid identifiers for components of transaction signing serializations. Components are combined in various orders to produce each of the valid "full" signing serializations.
Valid identifiers for full transaction signing serialization algorithms. Each full serialization is double-sha256 hashed to produce the digest which is signed.
All scenarios extend the default scenario, so the data
, transaction
(and
all transaction
properties), and value
properties are guaranteed to be
defined in an extended scenario definition.
The networks which can be referenced by an HD public or private key.
A private node in a Hierarchical Deterministic (HD) key tree. To confirm the
validity of this node, check the value of its valid
property.
Note, HD nodes are network-independent. A network is required only when encoding the node as an HD key or using a derived public key in an address.
A method which accepts a string and returns either the successfully resolved
bytecode or an error. The string will never be empty (''
), so resolution
can skip checking the string's length.
A deep-readonly utility type. Can be removed when a built-in alternative is added to TypeScript. Derived from: https://github.com/microsoft/TypeScript/issues/13923#issuecomment-557509399
An input which may optionally use a CompilationDirectiveUnlocking
as its
unlockingBytecode
property. During compilation, the final lockingBytecode
will be generated from this directive.
If RequireEstimate
is true
, all input directives must include an
estimate
scenario ID. See estimateTransaction
for details.
Operations define the behavior of an opcode in an InstructionSet
.
Operations should be written as efficiently as possible, and may safely
mutate the ProgramState
. If needed, the AuthenticationVirtualMachine
will clone the ProgramState
before providing it to an operation.
An output which may optionally use a CompilationDirectiveLocking
as its
lockingBytecode
property. During compilation, the final lockingBytecode
will be generated from this directive.
If EnableFeeEstimation
is true
, the satoshis
value may also be
undefined
(as estimated transactions always set output values to
invalidSatoshis
).
A potentially-malformed AuthenticationInstruction
. If malformed
is
true
, this could be either
ParsedAuthenticationInstructionPushMalformedLength
or
ParsedAuthenticationInstructionPushMalformedData
If the final instruction is a push operation which requires more bytes than
are available in the remaining portion of a serialized script, that
instruction will have a malformed
property with a value of true
.
.
An array of authentication instructions which may end with a malformed instruction.
Implementation note: this type can be improved by only marking the final element as potentially malformed. This is waiting on: https://github.com/Microsoft/TypeScript/issues/1360
The following type can be used when it doesn't produce the error,
A rest element must be last in a tuple type. [1256]
:
export type ParsedAuthenticationInstructions<Opcodes = number> = [
...AuthenticationInstruction<Opcodes>,
ParsedAuthenticationInstruction<Opcodes>
];
This type is a little complex because resulting HD nodes may not have a known
parent (defined parentIdentifier
) if the provided node does not have a
known parent and the path is either m
or M
(returning the provided node).
The contents of an AuthenticationTemplateScenario
without the name
and
description
.
Test a program state, returning an error message
A Transaction
which may optionally use compilation directives in place of
lockingBytecode
and unlockingBytecode
instances. During transaction
generation, these directives will be generated from these directives.
If EnableFeeEstimation
is true
, all input directives must include an
estimate
scenario ID, and the satoshis
value of each output may also be
undefined
(as estimated transactions always set output values to
invalidSatoshis
).
A transaction template which enables fee estimation. The template must
include an inputSatoshis
value (the total satoshi value of all
transaction inputs); all unlocking compilation directives must provide an
estimate
scenario ID which is used to estimate the size of the resulting
unlocking bytecode; and the satoshis
value of outputs is optional (all
satoshi values will be set to impossibleSatoshis
in the estimated
transaction).
A transaction template where all output amounts are provided (i.e. the values
of each "change" output has been decided). To estimate the final transaction
size given a transaction template (and from it, the required transaction
fee), see estimateTransaction
.
The network and address format in which a WIF-encoded private key is expected to be used.
WIF-encoding is generally used to serialize private keys for Pay to Public Key (P2PKH) addresses – each WIF-encoded private key specifies the compression of the public key to use in the P2PKH address:
mainnet
and testnet
indicate that the address should use the
compressed form of the derived public key (33 bytes, beginning with 0x02
or
0x03
) on the respective network.mainnet-uncompressed
and testnet-uncompressed
values
indicate that the address should use the uncompressed form of the public key
(65 bytes beginning with 0x04
) on the specified network.Flags to pass to secp256k1_context_create.
Flag to pass to secp256k1_ec_pubkey_serialize and secp256k1_ec_privkey_export.
The higher bits contain the actual data. Do not use directly.
All flags' lower 8 bits indicate what they're for. Do not use directly.
In ASCII, each pair of upper and lower case characters share the same 5 least significant bits.
Convert a bitcoin-style base58-encoded string to a Uint8Array.
See createBaseConverter
for format details.
The list of 32 symbols used in Bech32 encoding.
An object mapping each of the 32 symbols used in Bech32 encoding to their respective index in the character set.
Convert a Uint8Array to a bitcoin-style base58-encoded string.
See createBaseConverter
for format details.
The current strict virtual machine version used by the Bitcoin Cash (BCH) network.
The maximum uint64 value – an impossibly large, intentionally invalid value
for satoshis
. See Transaction.satoshis
for details.
The maximum Date (inclusive) which can be encoded by a transaction's
locktime
.
The maximum Unix timestamp (inclusive) which can be encoded by a
transaction's locktime
.
The minimum Date (inclusive) which can be encoded by a transaction's
locktime
.
The minimum Unix timestamp (inclusive) which can be encoded by a
transaction's locktime
.
Get the locking bytecode for a valid AddressContents
object. See
lockingBytecodeToAddressContents
for details.
For AddressContents
of type
AddressType.unknown
, this method returns
the payload
without modification.
the AddressContents
to encode
Method derived from Emscripten's preamble.js
Verify that every error in the provided array can be resolved by providing additional variables in the compilation data (rather than deeper issues, like problems with the authentication template or wallet implementation).
Note, errors are only recoverable if the "entity ownership" of each missing
identifier is known (specified in CompilationData
's entityOwnership
).
an array of compilation errors
Applies the error
to a state
.
Convert a string from Bitcoin ABC's script_tests.json
text-format to
bytecode. The string must be valid – this method attempts to convert all
unmatched tokens to BigInt
s.
the script in Bitcoin ABC's script_tests.json
text
format
Re-assemble a string of disassembled bytecode (see disassembleBytecode
).
a mapping of opcodes to their respective Uint8Array representation
the disassembled bytecode to re-assemble
Re-assemble a string of disassembled BCH bytecode (see
disassembleBytecodeBCH
).
Note, this method performs automatic minimization of push instructions.
the disassembled BCH bytecode to re-assemble
Re-assemble a string of disassembled BCH bytecode (see
disassembleBytecodeBTC
).
Note, this method performs automatic minimization of push instructions.
the disassembled BTC bytecode to re-assemble
Attempt to correct up to 2 errors in a CashAddress. The CashAddress must be properly formed (include a prefix and only contain Bech32 characters).
It is strongly advised that this method only be used under explicit user control. With enough errors, this method is likely to find a plausible correction for any address (but for which no private key exists). This is effectively equivalent to burning the funds.
Only 2 substitution errors can be corrected (or a single swap) – deletions and insertions (errors which shift many other characters and change the length of the payload) can never be safely corrected and will produce an error.
Errors can be corrected in both the prefix and the payload, but attempting to
correct errors in the prefix prior to this method can improve results, e.g.
for bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x
, the string
bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc
can be corrected, while
typo:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc
can not.
the CashAddress on which to attempt error correction
Attempt a series of compiler operations, skipping to the next operation if
the current operation returns a CompilerOperationSkip
(indicating it failed
and can be skipped). The finalOperation
may not be skipped, and must either
return CompilerOperationSuccess
or CompilerOperationError
.
an array of skippable operations to try
a final, un-skippable operation
A type-guard which checks if the provided instruction is malformed.
the instruction to check
A type-guard which checks if the final instruction in the provided array of instructions is malformed. (Only the final instruction can be malformed.)
A type-guard which confirms that the final instruction in the provided array is not malformed. (Only the final instruction can be malformed.)
Create a partial CompilationEnvironment
from an AuthenticationTemplate
by
extracting and formatting the scripts
and variables
properties.
Note, if this AuthenticationTemplate
might be malformed, first validate it
with validateAuthenticationTemplate
.
the AuthenticationTemplate
from which to extract the
compilation environment
Create a partial CompilationEnvironment
from an AuthenticationTemplate
,
virtualizing all script tests as unlocking and locking script pairs.
the authentication template from which to extract the compilation environment
Create a BCH Compiler
from an AuthenticationTemplate
and an optional set
of overrides.
the AuthenticationTemplate
from which to create the BCH
compiler
a compilation environment from which properties will be used to override properties of the default BCH environment
Convert a Base58Address to its respective locking bytecode.
This method returns the locking bytecode and network version. If an error occurs, an error message is returned as a string.
the CashAddress to convert
Convert a base64-encoded string to a Uint8Array.
Note, this method always completes. If validBase64
is not valid base64, an
incorrect result will be returned. If validBase64
is potentially malformed,
check it with isBase64
before calling this method.
a valid base64-encoded string to decode
Convert a padded bech32-encoded string (without checksum) to a Uint8Array, removing the padding. If the string is not valid Bech32, or if the array of 5-bit integers would require padding to be regrouped into 8-bit bytes, this method returns an error message.
This method is the reverse of binToBech32Padded
.
the padded bech32-encoded string to decode
Encode a positive BigInt into an unsigned 32-byte big-endian Uint8Array. This can be used to encoded numbers for cryptographic primitives like private keys, public keys, curve parameters, and signature points.
Negative values will return the same result as 0
, values higher than
2^256-1 will return the maximum expressible unsigned 256-bit value
(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
).
the BigInt to encode
Encode a positive BigInt as an 8-byte Uint64LE Uint8Array.
This method will return an incorrect result for values outside of the range
0
to 0xffff_ffff_ffff_ffff
.
the number to encode
Encode a positive BigInt as an 8-byte Uint64LE Uint8Array, clamping the
results. (Values exceeding 0xffff_ffff_ffff_ffff
return the same result as
0xffff_ffff_ffff_ffff
, negative values return the same result as 0
.)
the number to encode
Encode a positive BigInt as little-endian Uint8Array. Negative values will
return the same result as 0
.
the number to encode
Encode a positive BigInt as a Bitcoin VarInt (Variable-length integer).
Note: the maximum value of a Bitcoin VarInt is 0xffff_ffff_ffff_ffff
. This
method will return an incorrect result for values outside of the range 0
to
0xffff_ffff_ffff_ffff
.
the BigInt to encode (no larger than 0xffff_ffff_ffff_ffff
)
Convert a BigInt into the "Script Number" format. See
parseBytesAsScriptNumber
for more information.
the BigInt to encode as a Script Number
Decode a binary-encoded string into a Uint8Array.
E.g.: binStringToBin('0010101001100100')
→ new Uint8Array([42, 100])
Note, this method always completes. If binaryDigits
is not divisible by 8,
the final byte will be parsed as if it were prepended with 0
s (e.g. 1
is interpreted as 00000001
). If binaryDigits
is potentially malformed,
check it with isBinString
before calling this method.
Convert a Uint8Array to a base64-encoded string.
the Uint8Array to base64 encode
Convert a Uint8Array to a padded bech32-encoded string (without a checksum), adding padding bits as necessary to convert all bytes to 5-bit integers.
This method is the reverse of bech32PaddedToBin
.
the Uint8Array to bech32 encode
Decode an unsigned, 32-byte big-endian Uint8Array into a BigInt. This can be used to decode Uint8Array-encoded cryptographic primitives like private keys, public keys, curve parameters, and signature points.
If starting from a hex value, consider using the BigInt constructor instead:
BigInt(`0x${hex}`)
the Uint8Array to decode
Decode an 8-byte Uint64LE Uint8Array into a BigInt.
Throws if bin
is shorter than 8 bytes.
the Uint8Array to decode
Decode a big-endian Uint8Array of any length into a BigInt. If starting from a hex value, consider using the BigInt constructor instead:
BigInt(`0x${hex}`)
The bytes
parameter can be set to constrain the expected length (default:
bin.length
). This method throws if bin.length
is not equal to bytes
.
the Uint8Array to decode
the number of bytes to read (default: bin.length
)
Decode a little-endian Uint8Array of any length into a BigInt.
The bytes
parameter can be set to constrain the expected length (default:
bin.length
). This method throws if bin.length
is not equal to bytes
.
the Uint8Array to decode
the number of bytes to read (default: bin.length
)
Encode a Uint8Array into a binary-encoded string.
E.g.: binToBinString(Uint8Array.from([42, 100]))
→ '0010101001100100'
a Uint8Array to encode
Fill a new Uint8Array of a specific byte-length with the contents of a given Uint8Array, truncating or padding the Uint8Array with zeros.
the Uint8Array to resize
the desired byte-length
Encode a Uint8Array into a hexadecimal-encoded string.
E.g.: binToHex(new Uint8Array([42, 100, 255]))
→ '2a64ff'
a Uint8Array to encode
Decode a 2-byte Int16LE Uint8Array into a number.
Throws if bin
is shorter than 2 bytes.
the Uint8Array to decode
Decode a 4-byte Int32LE Uint8Array into a number.
Throws if bin
is shorter than 4 bytes.
the Uint8Array to decode
Decode a 2-byte Uint16LE Uint8Array into a number.
Throws if bin
is shorter than 2 bytes.
the Uint8Array to decode
Decode a 4-byte Uint32LE Uint8Array into a number.
Throws if bin
is shorter than 4 bytes.
the Uint8Array to decode
Decode a little-endian Uint8Array of any length into a number. For numbers
larger than Number.MAX_SAFE_INTEGER
(9007199254740991
), use
binToBigIntUintLE
.
The bytes
parameter can be set to constrain the expected length (default:
bin.length
). This method throws if bin.length
is not equal to bytes
.
the Uint8Array to decode
the number of bytes to read (default: bin.length
)
Decode a Uint8Array as a UTF-8 string.
the Uint8Array to decode
Convert a boolean into Script Number format (the type used to express boolean values emitted by several operations).
the boolean value to convert
Convert the checksum returned by cashAddressPolynomialModulo
to an array of
5-bit positive integers which can be Base32 encoded.
a 40 bit checksum returned by cashAddressPolynomialModulo
Perform the CashAddress polynomial modulo operation, which is based on the Bech32 polynomial modulo operation, but the returned checksum is 40 bits, rather than 30.
A.K.A. PolyMod
Array of 5-bit integers over which the checksum is to be computed
Convert a CashAddress polynomial to CashAddress string format.
an array of 5-bit integers representing the terms of a CashAddress polynomial
Convert a CashAddress to its respective locking bytecode.
This method returns the locking bytecode and network prefix. If an error occurs, an error message is returned as a string.
the CashAddress to convert
Note: this implementation does not safely clone elements within array properties. Mutating values within arrays will mutate those values in cloned program states.
Perform a simplified compilation on a Bitauth Templating Language (BTL) script containing only hex literals, bigint literals, UTF8 literals, and push statements. Scripts may not contain variables/operations, evaluations, or opcode identifiers (use hex literals instead).
This is useful for accepting complex user input in advanced interfaces,
especially for AddressData
and WalletData
.
Returns the compiled bytecode as a Uint8Array
, or throws an error message.
a simple BTL script containing no variables or evaluations
Parse, resolve, and reduce the selected script using the provided data
and
environment
.
Note, locktime validation only occurs if transactionContext
is provided in
the environment.
This method is generally for internal use. The compileScript
method is the
recommended API for direct compilation.
This method is generally for internal use. The compileScript
method is the
recommended API for direct compilation.
Returns false
if the target script ID doesn't exist in the compilation
environment (allows for the caller to generate the error message).
If the compilation produced errors, returns a CompilerOperationErrorFatal
.
If the compilation was successful, returns the compiled bytecode as a
Uint8Array
.
The current address index to be used for this compilation. The
addressIndex
gets added to each HdKey
s addressOffset
to calculate
the dynamic index (i
) used in each privateDerivationPath
or
publicDerivationPath
.
This is required for any compiler operation which requires derivation. Typically, the value is incremented by one for each address in a wallet.
A map of entity IDs to master HD private keys. These master HD private
keys are used to derive each HdKey
variable assigned to that entity (as
specified in CompilationEnvironment.entityOwnership
) according to its
privateDerivationPath
.
HD private keys may be encoded for either mainnet or testnet (the network information is ignored).
If both an HD private key (in hdPrivateKeys
) and HD public key (in
hdPublicKeys
) are provided for the same entity in the same compilation
(not recommended), only the HD private key is used.
A map of entity IDs to HD public keys. These HD public keys are used to
derive public keys for each HdKey
variable assigned to that entity (as
specified in CompilationEnvironment.entityOwnership
) according to its
publicDerivationPath
.
HD public keys may be encoded for either mainnet or testnet (the network information is ignored).
If both an HD private key (in hdPrivateKeys
) and HD public key (in
hdPublicKeys
) are provided for the same entity in the same compilation
(not recommended), the HD private key is used.
Returns either the properly generated coveredBytecode
or a
CompilerOperationErrorFatal
.
Modify a compiler operation to verify that certain properties exist in the
CompilationData
and CompilationEnvironment
before executing the provided
operation. If the properties don't exist, an error message is returned.
This is useful for eliminating repetitive existence checks.
Returns true if the outerRange
fully contains the innerRange
, otherwise,
false
.
the bounds of the outer range
the inner range to test
disallow the innerRange
from overlapping the
outerRange
(such that the outer start and end columns may not be equal) –
defaults to true
Derive the HD private node from a HD public node, given any non-hardened child private node.
an implementation of sha512
the parent HD public node for which to derive a private node
any non-hardened child private node of the parent
node (only the privateKey
and the childIndex
are required)
A common createAuthenticationProgram
implementation for most compilers.
Accepts the compiled contents of an evaluation and produces a
AuthenticationProgramCommon
which can be evaluated to produce the resulting
program state.
The precise shape of the authentication program produced by this method is critical to the determinism of BTL evaluations for the compiler in which it is used, it therefore must be standardized between compiler implementations.
the compiled bytecode to incorporate in the created authentication program
Create an "empty" common authentication program state, suitable for testing a VM/compiler.
Create an AuthenticationVirtualMachine to evaluate authentication programs
constructed from operations in the instructionSet
.
an InstructionSet
Create a BaseConverter
, which exposes methods for encoding and decoding
Uint8Array
s using bitcoin-style padding: each leading zero in the input is
replaced with the zero-index character of the alphabet
, then the remainder
of the input is encoded as a large number in the specified alphabet.
For example, using the alphabet 01
, the input [0, 15]
is encoded 01111
– a single 0
represents the leading padding, followed by the base2 encoded
0x1111
(15). With the same alphabet, the input [0, 0, 255]
is encoded
0011111111
- only two 0
characters are required to represent both
leading zeros, followed by the base2 encoded 0x11111111
(255).
This is not compatible with RFC 3548
's Base16
, Base32
, or Base64
.
If the alphabet is malformed, this method returns the error as a string
.
an ordered string which maps each index to a character,
e.g. 0123456789
.
Create a Compiler
from the provided compilation environment. This method
requires a full CompilationEnvironment
and does not instantiate any new
crypto or VM implementations.
the environment from which to create the compiler
Create a compiler using the default BCH environment.
Internally instantiates the necessary crypto and VM implementations – use
createCompiler
for more control.
a compilation environment from which properties
will be used to override properties of the default BCH environment – must
include the scripts
property
Synchronously create a compiler using the default common environment. Because this compiler has no access to Secp256k1, Sha256, or a VM, it cannot compile evaluations or operations which require key derivation or hashing.
a compilation environment from which properties
will be used to override properties of the default common compilation
environment – must include the scripts
property
Return an IdentifierResolutionFunction
for use in resolveScriptSegment
.
Initialize a new instruction set for the BCH virtual machine.
This is a meaningless but complete TransactionContextCommon
which uses 0
values for each property.
This is a meaningless but complete TransactionContextCommon
which uses a
different value for each property. This is useful for testing and debugging.
Convert a JavaScript Date
object to its equivalent transaction locktime
representation. The date
is rounded to the nearest second (the precision of
locktime
Dates).
Note, a locktime values greater than or equal to 500000000
See Transaction.locktime
for details.
the Date to convert to a locktime number
Convert a JavaScript Date
object to its equivalent transaction locktime
bytecode representation. The date
is rounded to the nearest second (the
precision of locktime
Dates).
Note: a block-based locktime can simply be encoded with numberToBinUint32LE
(provided it is no larger than the maximum, 499999999
).
the Date to convert to a locktime Uint8Array
Decode and validate a Base58Address, strictly checking the version and payload length.
For other address-like standards which closely follow the Base58Address
format (but have alternative version byte requirements), use
decodeBase58AddressFormat
.
an implementation of sha256 (a universal implementation is
available via instantiateSha256
)
the string to decode as a base58 address
Attempt to decode a Base58Address-formatted string. This is more lenient than
decodeCashAddress
, which also validates the address version.
Returns the contents of the address or an error message as a string.
an implementation of sha256 (a universal implementation is
available via instantiateSha256
)
the string to decode as a base58 address
Decode a Bech32-encoded string into an array of 5-bit integers.
Note, this method always completes. If validBech32
is not valid bech32,
an incorrect result will be returned. If validBech32
is potentially
malformed, check it with isBech32
before calling this method.
the bech32-encoded string to decode
Split a bitcoin-encoded signature into a signature and signing serialization type.
While a bitcoin-encoded signature only includes a single byte to encode the signing serialization type, a 3-byte forkId can be appended to the signing serialization to provide replay-protection between different forks. (See Bitcoin Cash's Replay Protected Sighash spec for details.)
Any compilation environment, where each data type may use either a single or multiple operations.