Import supertestnet/vanilla-js-browser-wallet with full upstream history

git-subtree-dir: upstream/vanilla-js-browser-wallet
git-subtree-mainline: 7298f2f9c5
git-subtree-split: 19ae5097f4
This commit is contained in:
Codex committed 2026-10-04 22:28:29 +00:00
commit 4f5f7dfcac
3 files changed
+824

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
@@ -0,0 +1,16 @@
# Vanilla JS Browser Wallet
A bare-bones bitcoin wallet for the base layer implemented in vanilla javascript
# How to use it
Go here: [https://supertestnet.github.io/vanilla-js-browser-wallet/wallet.html](https://supertestnet.github.io/vanilla-js-browser-wallet/wallet.html)
It should be pretty self explanatory, there's a send button, a receive button, and the homepage displays your balance and backup words (which you can hide after you write them down). That's all.
# Purpose
This wallet is intended for use by JS hackers who want to add a basic non-custodial bitcoin wallet to their website or chrome extension. You can copy the code from here and use it elsewhere.
# Limitations
The fee estimator needs some work. I wrote a spec sheet that has me create a variable that incorporates the dust limit plus some extra data depending on how many inputs a transaction has and at some point I got that variable mixed up with the dust limit itself. I need to fix that because right now this mistake causes the transaction builder to set the transaction fee higher than what you selected.
When you start the wallet it is also kinda slow to display your balance and your first unused address. I use blockstream.info as a chain backend and it queries them every five seconds for a bunch of addresses, namely, 20 or more change addresses plus 20 or more receive addresses (I set a gap limit of 20). When you start the wallet it won't show your balance until it's done with these queries. So be a little patient. Maybe I should add some sort of progress indicator.
@@ -0,0 +1,687 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Bitcoin browser wallet</title>
<script src="https://supertestnet.github.io/bitcoin-chess/js/qrcode.js"></script>
<script src="https://bitcoincore.tech/apps/bitcoinjs-ui/lib/bitcoinjs-lib.js"></script>
<script src="https://bundle.run/noble-secp256k1@1.2.14"></script>
<script src="https://bundle.run/bip39@3.0.4"></script>
<script src="https://bundle.run/bip32@2.0.6"></script>
<script src="https://bundle.run/buffer@6.0.3"></script>
<script>
function computeRawPrivkey( node ) {
return bitcoinjs.ECPair.fromPrivateKey( node.privateKey, { network: bitcoinjs.networks.testnet } ).__D.toString( "hex" );
}
function getNativeSegwitAddressFromPrivkeyHex( privkeyhex ) {
return bitcoinjs.payments.p2wpkh({ pubkey: bitcoinjs.ECPair.fromPrivateKey( buffer.Buffer.from( privkeyhex, "hex" ), { network: bitcoinjs.networks.testnet } ).publicKey, network: bitcoinjs.networks.testnet }).address;
}
function getPrivkeyHexFromPath( backupwords, path, index ) {
//standard segwit path is m/84'/0'/0'/0 so “path” should be 84'/0'/0' and “index” 0
var seed = bip39.mnemonicToSeedSync( backupwords );
var node = bip32.fromSeed( seed );
var path = "m/" + path + "/" + index;
var root = node;
var child = root.derivePath( path );
return computeRawPrivkey( child );
}
function getAddressFromPath( backupwords, path, index ) {
var privkey = getPrivkeyHexFromPath( backupwords, path, index );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
return address;
}
function getAddressBalance( address ) {
return new Promise( function( resolve, reject ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
var json = JSON.parse( xhttp.responseText );
var fullincome = json[ "chain_stats" ][ "funded_txo_sum" ] + json[ "mempool_stats" ][ "funded_txo_sum" ];
var fulloutgo = json[ "chain_stats" ][ "spent_txo_sum" ] + json[ "mempool_stats" ][ "spent_txo_sum" ];
resolve( fullincome - fulloutgo );
};
}
xhttp.open( "GET", "https://mempool.space/testnet/api/address/" + address, true );
xhttp.send();
});
}
function getCompressedPubkeyHexFromPrivkeyHex( privkeyhex ) {
return bitcoinjs.ECPair.fromPrivateKey( buffer.Buffer.from( privkeyhex, "hex" ), { network: bitcoinjs.networks.testnet } ).publicKey.toString( "hex" );
}
function getUTXOs( privkey ) {
var pubkey = getCompressedPubkeyHexFromPrivkeyHex( privkey );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
return new Promise( function( resolve, reject ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
var obj = {}
obj[ "address" ] = address;
obj[ "utxos" ] = [];
var esplorautxos = JSON.parse( xhttp.responseText );
esplorautxos.forEach( function( item, index ) {
var utxo = {}
utxo[ "tx_id" ] = item[ "txid" ];
utxo[ "output_number" ] = item[ "vout" ];
utxo[ "amount" ] = item[ "value" ];
utxo[ "privkey" ] = privkey;
utxo[ "pubkey" ] = pubkey;
obj[ "utxos" ].push( utxo );
});
resolve( obj );
}
}
xhttp.open( "GET", "https://mempool.space/testnet/api/address/" + address + "/utxo", true );
xhttp.send();
});
}
async function getAvailableUtxosFromReceivePath() {
return new Promise( async function( resolve, reject ) {
var available_utxos = [];
var i1 = 0;
var i2 = 0;
var i; for ( i=0; i<100000; i++ ) {
if ( i2 > 20 ) {
break;
}
var backupwords = localStorage[ "backup_words" ];
var path = "84'/0'/0'";
var privkey = getPrivkeyHexFromPath( backupwords, path, i1 + i2 );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
var balance = await getAddressBalance( address );
if ( balance < 1 ) {
i2 = Number( i2 ) + 1;
} else {
i1 = Number( i1 ) + 1;
var utxos_in_this_address = await getUTXOs( privkey );
available_utxos.push( utxos_in_this_address );
}
}
resolve( available_utxos );
});
}
async function getAvailableUtxosFromChangePath() {
return new Promise( async function( resolve, reject ) {
var available_utxos = [];
var i1 = 0;
var i2 = 0;
var i; for ( i=0; i<100000; i++ ) {
if ( i2 > 20 ) {
break;
}
var backupwords = localStorage[ "backup_words" ];
var path = "84'/0'/1'";
var privkey = getPrivkeyHexFromPath( backupwords, path, i1 + i2 );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
var balance = await getAddressBalance( address );
if ( balance < 1 ) {
i2 = Number( i2 ) + 1;
} else {
i1 = Number( i1 ) + 1;
var utxos_in_this_address = await getUTXOs( privkey );
available_utxos.push( utxos_in_this_address );
}
}
resolve( available_utxos );
});
}
async function checkAddresses() {
var available_utxos_1 = await getAvailableUtxosFromReceivePath();
var available_utxos_2 = await getAvailableUtxosFromChangePath();
available_utxos_2.forEach( function( item ) {
available_utxos_1.push( item );
});
sessionStorage[ "utxos" ] = JSON.stringify( available_utxos_1 );
}
function didThisAddressEverHaveMoney( address ) {
return new Promise( function( resolve, reject ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
var json = JSON.parse( xhttp.responseText );
if ( json[ "chain_stats" ][ "funded_txo_count" ] > 0 || json[ "mempool_stats" ][ "funded_txo_count" ] > 0 ) {
resolve( true );
}
resolve( false );
}
};
xhttp.open( "GET", "https://mempool.space/testnet/api/address/" + address, true );
xhttp.send();
});
}
async function getFirstUnusedAddress() {
var i; for ( i=0; i<100000; i++ ) {
var backupwords = localStorage[ "backup_words" ];
var path = "84'/0'/0'";
var privkey = getPrivkeyHexFromPath( backupwords, path, i );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
var hadMoney = await didThisAddressEverHaveMoney( address );
if ( !hadMoney ) {
return address;
}
}
}
async function getFirstUnusedChangeAddress() {
var i; for ( i=0; i<100000; i++ ) {
var backupwords = localStorage[ "backup_words" ];
var path = "84'/0'/1'";
var privkey = getPrivkeyHexFromPath( backupwords, path, i );
var address = getNativeSegwitAddressFromPrivkeyHex( privkey );
var hadMoney = await didThisAddressEverHaveMoney( address );
if ( !hadMoney ) {
return address;
}
}
}
async function displayBalance() {
await checkAddresses();
var utxos = JSON.parse( sessionStorage[ "utxos" ] );
var balance = 0;
alt_utxo_list = [];
utxos.forEach( function( item ) {
var i; for ( i=0; i<item[ "utxos" ].length; i++ ) {
balance = balance + Number( item[ "utxos" ][ i ][ "amount" ] );
alt_utxo_list.push( item[ "utxos" ][ i ] );
}
});
sessionStorage[ "alt_utxo_list" ] = JSON.stringify( alt_utxo_list );
return Number( balance ).toString();
}
function pushBTCpmt( rawtx ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if ( this.readyState == 4 && ( this.status > 199 && this.status < 300 ) ) {
var response = this.responseText;
console.log( "Your transaction was broadcasted, your txid is: " + response );
}
};
xhttp.open( "POST", "https://mempool.space/testnet/api/tx", true );
xhttp.send( rawtx );
}
function craftTransaction( selected_utxos, to_amount, to_address, change_address, change_amount, sats_per_byte ) {
if ( !to_amount ) {
return;
}
if ( change_amount != 0 && change_address != "none" ) {
var psbt = new bitcoinjs.Psbt({ network: bitcoinjs.networks.testnet });
var i; for ( i=0; i<selected_utxos.length; i++ ) {
psbt.addInput({
hash: selected_utxos[ i ][ "tx_id" ],
index: selected_utxos[ i ][ "output_number" ],
witnessUtxo: {
script: buffer.Buffer.from( '0014' + bitcoinjs.crypto.ripemd160( bitcoinjs.crypto.sha256( buffer.Buffer.from( selected_utxos[ i ][ "pubkey" ], "hex" ) ) ).toString( 'hex' ), 'hex' ),
value: selected_utxos[ i ][ "amount" ],
},
});
}
psbt.addOutput({
address: to_address,
value: to_amount,
});
psbt.addOutput({
address: change_address,
value: change_amount,
});
var keyPairSenders = [];
var i; for ( i=0; i<selected_utxos.length; i++ ) {
keyPairSenders.push( bitcoinjs.ECPair.fromPrivateKey( buffer.Buffer.from( selected_utxos[ i ][ "privkey" ], "hex" ), bitcoinjs.networks.testnet ) );
}
var i; for ( i=0; i<keyPairSenders.length; i++ ) {
psbt.signInput( i, keyPairSenders[ i ] );
}
var i; for ( i=0; i<keyPairSenders.length; i++ ) {
psbt.validateSignaturesOfInput( i );
}
psbt.finalizeAllInputs();
return psbt.extractTransaction().toHex();
} else {
var psbt = new bitcoinjs.Psbt({ network: bitcoinjs.networks.testnet });
var i; for ( i=0; i<selected_utxos.length; i++ ) {
psbt.addInput({
hash: selected_utxos[ i ][ "tx_id" ],
index: selected_utxos[ i ][ "output_number" ],
witnessUtxo: {
script: buffer.Buffer.from( '0014' + bitcoinjs.crypto.ripemd160( bitcoinjs.crypto.sha256( buffer.Buffer.from( selected_utxos[ i ][ "pubkey" ], "hex" ) ) ).toString( 'hex' ), 'hex' ),
value: selected_utxos[ i ][ "amount" ],
},
});
}
psbt.addOutput({
address: to_address,
value: to_amount,
});
var keyPairSenders = [];
var i; for ( i=0; i<selected_utxos.length; i++ ) {
keyPairSenders.push( bitcoinjs.ECPair.fromPrivateKey( buffer.Buffer.from( selected_utxos[ i ][ "privkey" ], "hex" ), bitcoinjs.networks.testnet ) );
}
var i; for ( i=0; i<keyPairSenders.length; i++ ) {
psbt.signInput( i, keyPairSenders[ i ] );
}
var i; for ( i=0; i<keyPairSenders.length; i++ ) {
psbt.validateSignaturesOfInput( i );
}
psbt.finalizeAllInputs();
return psbt.extractTransaction().toHex();
}
}
function addUtxosToTx( amount_plus_fee, utxos_available_for_this_transaction, utxos_in_this_transaction, sats_per_byte, this_addition_is_being_done_because_of_a_change_address = false, this_addition_is_being_done_after_the_total_transaction_size_is_known = false, total_transaction_size = 0, to_amount ) {
if ( !amount_plus_fee || amount_plus_fee == "" ) {
return;
}
var original_utxos_available_for_this_transaction = JSON.stringify( utxos_available_for_this_transaction );
var original_utxos_in_this_transaction = JSON.stringify( utxos_in_this_transaction );
var original_amount_plus_fee = amount_plus_fee;
console.log( "amount plus fee:", amount_plus_fee );
console.log( "utxos available for this transaction:", utxos_available_for_this_transaction );
console.log( "utxos in this transaction:", utxos_in_this_transaction );
if ( utxos_available_for_this_transaction.length < 1 ) {
alert( "You do not have enough money to send this transaction. Please top up your wallet or send a smaller amount." );
} else {
var largest_utxo_value = 0;
var largest_utxo_indexnum = 0;
var i; for ( i=0; i<utxos_available_for_this_transaction.length; i++ ) {
if ( utxos_available_for_this_transaction[ i ][ "amount" ] > largest_utxo_value ) {
largest_utxo_value = utxos_available_for_this_transaction[ i ][ "amount" ];
largest_utxo_indexnum = i;
}
}
console.log( "largest_utxo_indexnum", largest_utxo_indexnum );
console.log( "value of largest utxo", utxos_available_for_this_transaction[ largest_utxo_indexnum ][ "amount" ] );
utxos_in_this_transaction.push( utxos_available_for_this_transaction.splice( largest_utxo_indexnum, 1 )[ 0 ] );
if ( !this_addition_is_being_done_after_the_total_transaction_size_is_known ) {
amount_plus_fee = amount_plus_fee + ( 50 * sats_per_byte );
console.log( "the new amount_plus_fee, accounting for the new inputs, is", amount_plus_fee );
}
console.log( "number of utxos in this transaction", utxos_in_this_transaction.length );
var sum_of_the_values_of_each_input_to_this_transaction = 0;
var i; for ( i=0; i<utxos_in_this_transaction.length; i++ ) {
console.log( "utxo in this transaction whose value we are currently checking so we can sum up the total value of all utxos in this transaction and check if it is greater than or equal to the total amount we are sending including the mining fee (btw the total amount including the mining fee is " + amount_plus_fee + ")", i );
console.log( "current utxo", utxos_in_this_transaction[ i ] );
console.log( "amount of current utxo", utxos_in_this_transaction[ i ][ "amount" ] );
sum_of_the_values_of_each_input_to_this_transaction = sum_of_the_values_of_each_input_to_this_transaction + utxos_in_this_transaction[ i ][ "amount" ];
console.log( "the sum of the values of each input to this transaction is", sum_of_the_values_of_each_input_to_this_transaction );
}
if ( sum_of_the_values_of_each_input_to_this_transaction < amount_plus_fee ) {
console.log( "the sum of the values of each input to this transaction, i.e.", sum_of_the_values_of_each_input_to_this_transaction, "was less than the amount we need in the inputs, i.e.", amount_plus_fee, "so we need to run this function again with a higher amount_plus_fee value" );
return addUtxosToTx( amount_plus_fee, utxos_available_for_this_transaction, utxos_in_this_transaction, sats_per_byte, false, this_addition_is_being_done_after_the_total_transaction_size_is_known, total_transaction_size, to_amount );
} else {
if ( !this_addition_is_being_done_because_of_a_change_address ) {
if ( total_transaction_size > 0 ) {
var change_amount = sum_of_the_values_of_each_input_to_this_transaction - ( to_amount + ( total_transaction_size * sats_per_byte ) );
} else {
var change_amount = sum_of_the_values_of_each_input_to_this_transaction - amount_plus_fee;
}
console.log( "the sum of the values of each input to this transaction is", sum_of_the_values_of_each_input_to_this_transaction );
console.log( "amount plus fee", amount_plus_fee );
console.log( "the change amount should be one of two values, either the first number minus the second number, i.e.", sum_of_the_values_of_each_input_to_this_transaction - amount_plus_fee, "or the first number minus the to_amount minus the total transaction size -- as long as I know it, currently it is thought to be", total_transaction_size, "and if that number is 0 it just means I do not know it -- multiplied by the sats_per_byte value, which is", sats_per_byte, "for a total of", sum_of_the_values_of_each_input_to_this_transaction - ( to_amount + ( total_transaction_size * sats_per_byte ) ) );
if ( change_amount > 0 ) {
console.log( "there is change left over, namely", change_amount, "-- so we have to check if that is more than the dust limit" );
} else {
console.log( "there is no change left over so I do not need a change output, yay!" );
}
if ( change_amount >= 250 ) {
console.log( "the change amount --", change_amount, "-- is equal to or more than the dust limit of this wallet, which is 250. (It used to be 250 + 50 * sats_per_byte i.e.", ( 250 + 50 * sats_per_byte ), "because I added some to the dust limit so that the change amount would not go lower than the dust limit once I add another output, but this caused problems and 250 is already a bit high anyway so I put it back to just 250.) So I have to redo steps 4-9. I used to use a new amount_plus_fee of the previous amount_plus_fee plus 50*sats_per_byte, i.e.", original_amount_plus_fee + 50*sats_per_byte, "because I figured the transaction size would have to rise by about 50 bytes, but it causes problems so now I am redoing it without changing anything. Also I have to remember to use the old values of utxos_available_for_this_transaction and utxos_in_this_transaction" );
var we_need_a_change_address = true;
// new_amount_plus_fee = original_amount_plus_fee + ( 50*sats_per_byte );
new_amount_plus_fee = original_amount_plus_fee;
console.log( "original utxos available:", JSON.parse( original_utxos_available_for_this_transaction ) );
console.log( "original utxos in this tx:", JSON.parse( original_utxos_in_this_transaction ) );
return addUtxosToTx( new_amount_plus_fee, JSON.parse( original_utxos_available_for_this_transaction ), JSON.parse( original_utxos_in_this_transaction ), sats_per_byte, true, this_addition_is_being_done_after_the_total_transaction_size_is_known, total_transaction_size, to_amount );
} else {
console.log( "there is a small possibility that this was mentioned earlier (if he change output was exactly equal to 0), but in case it was not, be aware that there is no change output because the change amount was lower than my dust threshhold and will therefore be dropped. That is good because it means I am using my coins efficiently and saving on fees" );
var we_need_a_change_address = false;
}
console.log( "sum of the values of each input to this transaction", sum_of_the_values_of_each_input_to_this_transaction );
console.log( "amount_plus_fee", amount_plus_fee );
console.log( "change_amount", change_amount );
var array = [];
array[ 0 ] = utxos_available_for_this_transaction;
array[ 1 ] = utxos_in_this_transaction;
array[ 2 ] = amount_plus_fee;
array[ 3 ] = change_amount;
array[ 4 ] = "the next field is true if we need a change address";
array[ 5 ] = this_addition_is_being_done_because_of_a_change_address;
return array;
} else {
if ( total_transaction_size > 0 ) {
var change_amount = sum_of_the_values_of_each_input_to_this_transaction - ( to_amount + ( total_transaction_size * sats_per_byte ) );
} else {
var change_amount = sum_of_the_values_of_each_input_to_this_transaction - amount_plus_fee;
}
console.log( "ok this is part of the change path, my change value is", change_amount );
var array = [];
array[ 0 ] = utxos_available_for_this_transaction;
array[ 1 ] = utxos_in_this_transaction;
array[ 2 ] = amount_plus_fee;
array[ 3 ] = change_amount;
array[ 4 ] = "the next field is true if we need a change address";
array[ 5 ] = this_addition_is_being_done_because_of_a_change_address;
console.log( "I need a change address, right?", array[ 5 ] );
return array;
}
}
}
}
async function sendFromUtxoSetToAddress( toamount, toaddress, sats_per_byte, utxos_available_for_this_transaction, utxos_in_this_transaction ) {
console.log( "to amount", toamount );
console.log( "sats per byte", sats_per_byte );
var amount_plus_fee = toamount + ( 150 * sats_per_byte );
console.log( "amount_plus_fee", amount_plus_fee );
if ( !utxos_available_for_this_transaction ) {
var utxos_available_for_this_transaction = JSON.parse( sessionStorage[ "alt_utxo_list" ] );
}
if ( !utxos_in_this_transaction ) {
var utxos_in_this_transaction = [];
}
var original_utxos_available_for_this_transaction = JSON.stringify( utxos_available_for_this_transaction );
var original_utxos_in_this_transaction = JSON.stringify( utxos_in_this_transaction );
var array = addUtxosToTx( amount_plus_fee, utxos_available_for_this_transaction, utxos_in_this_transaction, sats_per_byte, false, false, 0, toamount );
console.log( "here is array item 0:", array[ 0 ] );
console.log( "ok now I am checking if array item 0 satisfies an if condition:" );
if ( array[ 0 ].length > 0 ) {
console.log( "hmm, it did" );
} else {
console.log( "yay, it did not!" );
}
if ( array[ 0 ].length > 0 && array[ 1 ] && array[ 2 ] && array[ 3 ] && array[ 4 ] && array[ 5 ] ) {
var adjusted_utxos_available_for_this_transaction = array[ 0 ];
var adjusted_utxos_in_this_transaction = array[ 1 ];
amount_plus_fee = array[ 2 ];
} else {
var adjusted_utxos_available_for_this_transaction = [];
var adjusted_utxos_in_this_transaction = [];
amount_plus_fee = 0;
}
var adjusted_utxos_in_this_transaction = array[ 1 ];
amount_plus_fee = array[ 2 ];
if ( array[ 5 ] ) {
var change_amount = array[ 3 ];
console.log( "change_amount", change_amount );
var change_address = await getFirstUnusedChangeAddress();
} else {
var change_amount = 0;
var change_address = "none";
}
console.log( "adjusted_utxos_available_for_this_transaction", adjusted_utxos_available_for_this_transaction );
console.log( "adjusted_utxos_in_this_transaction", adjusted_utxos_in_this_transaction );
console.log( "amount_plus_fee", amount_plus_fee );
var txhex = craftTransaction( adjusted_utxos_in_this_transaction, toamount, toaddress, change_address, change_amount, sats_per_byte );
console.log( txhex );
var tx = bitcoinjs.Transaction.fromHex( txhex );
var virtual_bytes = tx.virtualSize();
var real_fee = virtual_bytes * sats_per_byte;
var new_amount_plus_fee = toamount + real_fee;
console.log( "now I will check what the original utxos available are" );
console.log( original_utxos_available_for_this_transaction );
console.log( JSON.parse( original_utxos_available_for_this_transaction ) );
console.log( "I will also check what the original utxos in the transaction are", JSON.parse( original_utxos_in_this_transaction ) );
console.log( "Ok I am about to rerun addUtxosToTx with the new fee in mind. The most important variable for this is new_amount_plus_fee, which is the amount I am sending,", toamount, "plus a variable where the number of actual bytes in this transaction, i.e.", virtual_bytes, "is multiplied by the sats per byte value, i.e.", sats_per_byte, "to give a result of", real_fee, "which I add to my to_amount to get a total new_amount_plus_fee of", new_amount_plus_fee );
var new_array = addUtxosToTx( new_amount_plus_fee, JSON.parse( original_utxos_available_for_this_transaction ), JSON.parse( original_utxos_in_this_transaction ), sats_per_byte, false, true, virtual_bytes, toamount );
console.log( "I need a change address, right? (This should be at least the second time I am asking this)", new_array[ 5 ] );
var new_adjusted_utxos_available_for_this_transaction = new_array[ 0 ];
var new_adjusted_utxos_in_this_transaction = new_array[ 1 ];
new_amount_plus_fee = new_array[ 2 ];
var new_change_amount = new_array[ 3 ];
if( Number( new_array[ 3 ] ) >= 250 && ( !change_address || change_address == "none" ) && new_array[ 5 ] ) {
var change_address = await getFirstUnusedChangeAddress();
}
var new_txhex = craftTransaction( new_adjusted_utxos_in_this_transaction, toamount, toaddress, change_address, new_change_amount, sats_per_byte );
console.log( new_txhex );
var new_tx = bitcoinjs.Transaction.fromHex( new_txhex );
var new_virtual_bytes = tx.virtualSize();
if ( new_virtual_bytes == virtual_bytes ) {
console.log( "yay! The transaction is ready and here is its hex:", new_txhex );
return new_txhex;
} else {
alert( "I tried to craft your transaction twice and I kept getting errors. Please contact the developer of this wallet for assistance." );
}
}
function createQR( content ) {
var dataUriPngImage = document.createElement( "img" ),
s = QRCode.generatePNG( content, {
ecclevel: "M",
format: "html",
fillcolor: "#FFFFFF",
textcolor: "#373737",
margin: 4,
modulesize: 8,
});
dataUriPngImage.src = s;
dataUriPngImage.id = "qr_code";
dataUriPngImage.style.display = "block";
dataUriPngImage.style.margin = "auto";
dataUriPngImage.style.maxWidth = "300px";
return dataUriPngImage;
}
</script>
<style>
* {
box-sizing: border-box;
margin: 0px;
}
html, body {
height: 100%;
margin: 0px;
}
#wallet {
position: relative;
border: 1px solid black;
width: 100%;
max-width: 500px;
min-height: 900px;
margin: auto;
border-radius: 20px;
text-align: center;
padding: 10px;
}
#wallet-home {
}
#balance-line {
display: inline-block;
max-height: 25px;
height: 25px;
margin-bottom: 5px;
}
#denomination {
display: none;
}
#backup-line {
display: none;
position: absolute;
bottom: 10px;
width: 95%;
margin: auto;
border: 1px solid black;
}
#backup-instructions {
text-decoration: underline;
width: 80%;
margin: auto;
margin-top: 20px;
margin-bottom: 20px;
}
#backup-words {
margin-bottom: 20px;
}
#receive-tab {
display: none;
}
#address-line {
margin-bottom: 20px;
}
#send-tab {
display: none;
}
#address-input-line {
max-width: 400px;
text-align: left;
margin: auto;
}
#address-input-line input {
width: 100%;
margin-bottom: 20px;
}
#send-money-button-line {
text-align: center;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div id="wallet">
<div id="home-tab">
<div id="balance-label">
Balance
</div>
<div id="balance-line">
<span id="balance">
<img src="https://i.gifer.com/origin/34/34338d26023e5515f6cc8969aa027bca_w200.gif" style="width: 100%; max-width: 25px; height: 25px;" />
</span> <span id="denomination">sats</span>
</div>
<div>
<button class="send-button">Send</button>
<button class="receive-button">Receive</button>
</div>
<div id="backup-line">
<p id="backup-instructions">
Write down your backup words or you may lose your money
</p>
<p style="display: inline-block;margin: 10px;position: absolute;right: 0px;top: 0px;cursor: pointer;" id="hide-backup-line">×</p>
<p id="backup-words">
</p>
</div>
</div>
<div id="receive-tab">
<div id="receive-label">
Receive
</div>
<div id="address-qr">
<img src="https://i.gifer.com/origin/34/34338d26023e5515f6cc8969aa027bca_w200.gif" style="width: 100%; max-width: 300px; height: 300px;" />
</div>
<div id="address-line">
<span id="address">
</span>
</div>
<div>
<button class="home-button">Home</button>
</div>
</div>
<div id="send-tab">
<div id="send-label">
Send
</div>
<div id="address-input-line">
<p>
<div id="address-input-label">
Address
</div>
<input type="text" name="send-address-input" id="send-address-input" placeholder="a bitcoin address e.g. tb1ql7w62elx9ucw4pj5lgw4l028hmuw80sndtntxt" />
</p>
<p>
<div id="amount-input-label">
Amount
</div>
<input type="number" step="1" name="send-amount-input" id="send-amount-input" placeholder="an amount in sats e.g. 503505" />
</p>
<div id="sliderange">
<p>Sats per byte: <span id="sats_per_byte">1</span></p>
<input id="sats_range" type="range" min="1" max="100" value="1">
</div>
<script>
var slider = document.getElementById( "sats_range" );
var output = document.getElementById( "sats_per_byte" );
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
<p id="send-money-button-line">
<button id="send-money-button">Send</button>
</p>
</div>
<div>
<button class="home-button">Home</button>
</div>
</div>
</div>
<script>
//start the wallet and check its balance every five seconds
if ( !localStorage[ "backup_words" ] || localStorage[ "seed_phrase" ] == "" ) {
localStorage[ "backup_words" ] = bip39.generateMnemonic();
}
document.getElementById( "backup-words" ).innerText = localStorage[ "backup_words" ];
async function startWallet() {
var balance = await displayBalance();
var firstUnusedAddress = await getFirstUnusedAddress();
document.getElementById( "balance" ).innerText = balance;
document.getElementById( "address" ).innerText = firstUnusedAddress;
document.getElementById( "address-qr" ).innerText = "";
document.getElementById( "address-qr" ).append( createQR( "bitcoin:" + firstUnusedAddress ) );
}
function startLoop() {
startWallet();
setTimeout( function() {startLoop();}, 5000 );
}
startLoop();
//make the receive button display the receive tab
var i; for ( i=0; i<document.getElementsByClassName( "receive-button" ).length; i++ ) {
document.getElementsByClassName( "receive-button" )[ i ].addEventListener( "click", function() {
document.getElementById( "home-tab" ).style.display = "none";
document.getElementById( "receive-tab" ).style.display = "block";
document.getElementById( "send-tab" ).style.display = "none";
});
}
//make the home button display the home tab
var i; for ( i=0; i<document.getElementsByClassName( "home-button" ).length; i++ ) {
document.getElementsByClassName( "home-button" )[ i ].addEventListener( "click", function() {
document.getElementById( "home-tab" ).style.display = "block";
document.getElementById( "receive-tab" ).style.display = "none";
document.getElementById( "send-tab" ).style.display = "none";
});
}
//make the send button display the send tab
var i; for ( i=0; i<document.getElementsByClassName( "send-button" ).length; i++ ) {
document.getElementsByClassName( "send-button" )[ i ].addEventListener( "click", function() {
document.getElementById( "home-tab" ).style.display = "none";
document.getElementById( "receive-tab" ).style.display = "none";
document.getElementById( "send-tab" ).style.display = "block";
});
}
//make the backup instructions disappear when x'd out
if ( !sessionStorage[ "hide-backup-instructions" ] || sessionStorage[ "hide-backup-instructions" ] == "false" ) {
document.getElementById( "backup-line" ).style.display = "block";
}
document.getElementById( "hide-backup-line" ).addEventListener( "click", function() {
sessionStorage[ "hide-backup-instructions" ] = true;
document.getElementById( "backup-line" ).style.display = "none";
});
//make the send money button send money
document.getElementById( "send-money-button" ).addEventListener( "click", async function() {
var to_address = document.getElementById( "send-address-input" ).value;
var amount_to_send = Number( document.getElementById( "send-amount-input" ).value );
var sats_per_byte = Number( document.getElementById( "sats_per_byte" ).innerText );
var txhex = await sendFromUtxoSetToAddress( amount_to_send, to_address, sats_per_byte );
console.log( "txhex:", txhex );
pushBTCpmt( txhex );
});
</script>
</body>
</html>