Skip to content

Commit 9c486a4

Browse files
committed
btc: Add lookup() script utility and some simple composite opcodes
1 parent 59306c6 commit 9c486a4

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/stdlib/btc.minsc

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,36 @@ fn tx::sighash::tr_leaf($tx, $vin, $script_leaf, $utxos, $sighash_ty) = psbt::si
5858

5959
// TOOD tx::sighash::sw0() with just the signed utxo & tx::sighash::presw() with just the utxo's script
6060

61+
//
62+
// Script utilities
63+
//
64+
65+
// Verify that the top stack element is exactly 1 or 0
66+
OP::MINIMAL_BOOL = `OP_DUP OP_SIZE OP_EQUALVERIFY`;
67+
68+
// MUL for small constant numbers
69+
OP::2MUL = `OP_DUP OP_ADD`;
70+
OP::3MUL = `OP_DUP*2 OP_ADD*2`;
71+
OP::4MUL = OP::2MUL*2;
72+
OP::5MUL = `OP_DUP OP::4MUL OP_ADD`;
73+
OP::6MUL = `OP::3MUL OP::2MUL`;
74+
OP::7MUL = `OP_DUP OP::6MUL OP_ADD`;
75+
OP::8MUL = `OP::4MUL OP::2MUL`;
76+
OP::9MUL = OP::3MUL*2;
77+
78+
// Static lookup table by index
79+
// For example: `3 lookup([10,11,12,13,14])` will leave `13` on the stack
80+
// stack in: <index>, stack out: <values[index]>
81+
fn lookup($values) = `
82+
OP_TOALTSTACK // keep index number aside
83+
reverse($values) // reversed so that index 0 gets the first element
84+
OP_FROMALTSTACK OP_PICK // get index lookup result
85+
OP_TOALTSTACK // keep lookup result aside
86+
OP_2DROP*(len($values)/2) OP_DROP*(len($values)%2) // cleanup table
87+
OP_FROMALTSTACK
88+
`;
89+
// h/t https://github.com/coins/bitcoin-scripts/
90+
6191
//
6292
// Script Looping utilities
6393
//

src/stdlib/stdlib.minsc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ fn some($arr, $fn) = foldUntil($arr, false, |$acc, $el| if $fn($el) then true:
3232
fn every($arr, $fn) = !some($arr, |$el| !$fn($el));
3333

3434
fn contains($arr, $needle) = some($arr, |$el| $el == $needle);
35+
fn reverse($arr) = map(keys($arr), |$i| $arr.(len($arr)-$i-1));
3536

3637
fn concat($xs) = reduce($xs, |$acc, $x| $acc + $x);
3738
sum = concat; // works for arrays, bytes, strings and numbers

0 commit comments

Comments
 (0)