Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support sBTC alpha using bridge as tx generation tool #193

Merged
merged 2 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"classnames": "^2.3.2",
"flowbite": "^1.6.5",
"flowbite-svelte": "^0.39.1",
"sbtc-bridge-lib": "^1.0.26",
"sbtc-bridge-lib": "^1.0.28",
"sockjs": "^0.3.24",
"svelte-local-storage-store": "^0.5.0",
"svelte-qrcode": "^1.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/deposit/op_return/DepositForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@
timeLineStatus = 2;
dispatch('time_line_status_change', { timeLineStatus });
} catch(err:any) {
amountErrored = 'Please enter an amount thats more than the minimum threshold of ' + piTx.fee
amountErrored = 'Please enter an amount thats more than the minimum threshold'
makeFlash(document.getElementById(input2Data.field))
}
} else if (button.target === 'back') {
Expand Down
14 changes: 11 additions & 3 deletions src/lib/components/deposit/op_return/SignTransactionWeb.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,13 @@ const broadcastTransaction = async (psbtHex:string) => {
console.log('Error saving pegin request', err)
// duplicate.. ok to ignore
}
} else {
} else if (resp) {
errMessage = (resp.error);
broadcasted = false;
errorReason = 'Unable to broadcast the transaction - <a href="https://github.com/Stacks-Builders/sbtc-bridge-web/issues" target="_blank">please report ths error</a>.'
} else {
broadcasted = false;
errorReason = 'Unknown response from transaction broadcast - <a href="https://github.com/Stacks-Builders/sbtc-bridge-web/issues" target="_blank">please report ths error</a>.'
}
} catch (err:any) {
console.log('Broadcast error: ', err)
Expand All @@ -125,7 +128,12 @@ onMount(async () => {
currentTx = hex.encode(tx.toPSBT());

} else {
currentTx = hex.encode((await piTx?.buildOpReturnTransaction()).toPSBT());
try {
currentTx = hex.encode((await piTx?.buildOpReturnTransaction()).toPSBT());
} catch (err:any) {
console.log('Input error: ', err)
errorReason = 'Not enough BTC in your wallet currently to cover the withdrawal fees.'
}
}
inited = true;
})
Expand Down Expand Up @@ -155,7 +163,7 @@ onMount(async () => {
{/if}
</div>
{:else if errorReason}
<div class="">
<div class="my-5">
{#if errorReason}<div class="text-warning-400"><p>{@html errorReason}</p></div>{/if}
</div>
<div class="">
Expand Down
37 changes: 37 additions & 0 deletions src/lib/components/withdraw/WithdrawForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
import Banner from '$lib/components/shared/Banner.svelte';
import SignTransactionWeb from "$lib/components/deposit/op_return/SignTransactionWeb.svelte";
import { bitcoinToSats, satsToBitcoin } from '$lib/utils'
import { signMessageDirect, btcAddress, address } from '$lib/stacks_connect_bug';
import { verifyMessageSignature, verifyMessageSignatureRsv } from '@stacks/encryption';
import { hex } from '@scure/base';

const dispatch = createEventDispatcher();

Expand Down Expand Up @@ -105,6 +108,38 @@
}
*/

const doClickShowInvoice = async () => {
//// bug hunt
const amt = bitcoinToSats(input2Data.value)
verifySBTCAmount(amt, $sbtcConfig.addressObject!.sBTCBalance, 0);
piTx.fromBtcAddress = btcAddress;
piTx.pegInData.stacksAddress = address;
piTx.pegInData.amount = amt;
const script = piTx.getDataToSign();
console.log('message: ' + script)
const noPrefixSignature = signMessageDirect(script);
let signature = noPrefixSignature.signature
//const sig = signature.substring(0, signature.length - 2)
//signature = '00' + sig
//let verified1 = verifyMessageSignature({ signature, message: script, publicKey: noPrefixSignature.publicKey });
//if (!verified1) verified1 = verifyMessageSignatureRsv({ signature, message: script, publicKey: noPrefixSignature.publicKey })
// throw new Error('verifyMessageSignature - signature is not valid')

piTx.signature = signature;
peginRequest = piTx.getOpReturnPeginRequest();
////
peginRequest.originator = $sbtcConfig.addressObject!.stxAddress; // retain the sender in case the address in UI changes.
const conf:SbtcConfig = $sbtcConfig;
conf.sigData = signature;
sbtcConfig.update(() => conf);
//pegout = piTx.getOpDropPeginRequest();
timeLineStatus = 2;
if (!$sbtcConfig.userSettings?.useOpDrop) {
timeLineStatus = 4;
}
dispatch('time_line_status_change', { timeLineStatus });
}

const doClicked = async (event:any) => {
amountErrored = undefined;
const button = event.detail;
Expand All @@ -114,6 +149,8 @@
verifySBTCAmount(amt, $sbtcConfig.addressObject!.sBTCBalance, 0);
piTx.pegInData.amount = amt;
const script = piTx.getDataToSign();
//const script = hex.encode(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))
console.log('HASH: ' + script)
await signMessage(async function(sigData:any, message:Uint8Array) {
piTx.signature = sigData.signature;
try {
Expand Down
5 changes: 3 additions & 2 deletions src/lib/domain/PegOutTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default class PegOutTransaction implements PegOutTransactionI {
fees: Array<number> = [20000, 35000, 50000];
fee = 0;
scureFee = 0;
dust = 500;
dust = 2000;
feeInfo: {
low_fee_per_kb: number;
medium_fee_per_kb: number;
Expand Down Expand Up @@ -131,6 +131,7 @@ export default class PegOutTransaction implements PegOutTransactionI {
this.addInputs(tx, false);
if (!this.signature) throw new Error('Signature of the amount and output 2 scriptPubKey is missing.')
const data = this.buildData(this.signature, false)
console.log('buildOpReturnTransaction: ' + hex.encode(data))
tx.addOutput({ script: btc.Script.encode(['RETURN', data]), amount: 0n });
const change = this.inputAmt(tx) - (this.dust + this.fee);
if (change > 0) tx.addOutputAddress(this.fromBtcAddress, BigInt(change), net);
Expand Down Expand Up @@ -358,7 +359,7 @@ export default class PegOutTransaction implements PegOutTransactionI {
}

private addInputs = (tx:btc.Transaction, feeCalc:boolean) => {
const fee = (feeCalc) ? 1000 : this.fee;
const fee = (feeCalc) ? this.dust : this.fee;
const bar = fee + this.dust + revealFee;
let amt = 0;
for (const utxo of this.addressInfo.utxos) {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/sbtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const defaultSbtcConfig:SbtcConfig = {
pegOutTransaction: undefined,
keys: {} as KeySet,
userSettings: {
useOpDrop: true,
useOpDrop: false,
debugMode: false,
testAddresses: false,
currency: {
Expand Down
22 changes: 14 additions & 8 deletions src/lib/stacks_connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import { CONFIG } from '$lib/config';
import { c32address, c32addressDecode } from 'c32check';
import { sbtcConfig } from '$stores/stores'
import { fetchUserBalances } from '$lib/bridge_api'
import { fetchUserBalances, sign } from '$lib/bridge_api'
import type { SbtcConfig } from '$types/sbtc_config';
import { StacksTestnet, StacksMainnet, StacksMocknet } from '@stacks/network';
import { openSignatureRequestPopup } from '@stacks/connect';
import { AppConfig, UserSession, showConnect, getStacksProvider } from '@stacks/connect';
import type { AddressObject } from 'sbtc-bridge-lib'
import { verifyMessageSignature } from '@stacks/encryption';

const appConfig = new AppConfig(['store_write', 'publish_data']);
export const userSession = new UserSession({ appConfig }); // we will use this export from other files
Expand Down Expand Up @@ -179,19 +180,24 @@ export async function loginStacksJs(callback:any):Promise<any> {
}
}

export function signMessage(callback:any, script:string) {
export function signMessage(callback:any, message:string) {
openSignatureRequestPopup({
message: script,
message,
network: getStacksNetwork(), // for mainnet, `new StacksMainnet()`
appDetails: appDetails(),
onFinish(value) {
console.log('Signature of the message', value.signature);
console.log('Use public key:', value.publicKey);
callback(value, script);
},
onFinish({ publicKey, signature }) {
let newSig = signature.substring(0, signature.length - 2);
const recByte = signature.substring(signature.length - 2);
newSig = recByte + newSig
const verified1 = verifyMessageSignature({ signature: newSig, message, publicKey });
if (!verified1) throw new Error('verifyMessageSignature - signature is not valid')
callback({ publicKey, signature: newSig }, message);
}
});
}
/**

*/
export function logUserOut() {
return userSession.signUserOut();
}
Expand Down
55 changes: 55 additions & 0 deletions src/lib/stacks_connect_bug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

import { bytesToHex } from '@stacks/common';
import { hashMessage } from '@stacks/encryption';
import {
createStacksPrivateKey,
getPublicKey,
publicKeyToString,
signMessageHashRsv,
} from '@stacks/transactions';
import { hex } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { concatBytes, utf8ToBytes } from '@stacks/common';

export const keyChain = {
"mnemonic": "foster raise devote wear great volcano spring chapter among violin bleak syrup rent sphere coyote client govern spirit good risk cruise twice trick jealous",
"keyInfo": {
"privateKey": "b9a2ed36c4ba45e0cb610281dbbed9082d861b3523792b254afcb111af8765e801",
"publicKey": "03b5c5e9e5dee7b2237cd1b03583f410c0d784b9fd7906440f11d089ef6a4315de",
"address": "ST2GEN9CVCJNZPDH7Z7NPWRG6Z67GH3WWYAS4DGRA",
"btcAddress": "mvBoWJKijz38oTSJphUVNwRAkXtbJa6cUg",
"wif": "cToZ7x3Ju96xHxS8ZuEFmGxqMWJDbAQWsUgh48CG5zgtkzt1yRJj",
"index": 0
}
}
const keyChainTM = {
mnemonic: "tongue share ketchup verb online render syrup foam sock dice word indoor immune main shy parrot private roof weasel good nasty depth brass latin",
wif: "cTUr9E29ZSU7DM2BZasiRbosSSaTxkweFDDgALq9X4HTTfeLgHj7",
private_key: "b00359f021f31a172d0f1bdce77ff8484d826b26dcb8a87149ad0158a7fa076b",
public_key: "0x0219d8b596270530a70ab714e3df1e2c9dc47f2c4a58f764e8d6e30f71eb5be3e4",
stacks_address: "ST16DSD4NMCS0F1JTPR88114A9YPC86X2SM4D9K52",
bitcoin_taproot_address_tweaked: "tb1pe5awed3ly579dg4arvfjclqwqagcvys94j4jnfzz9x0m5097yaqqp3fd47",
bitcoin_taproot_address_untweaked: "tb1pr8vtt938q5c2wz4hzn3a783vnhz87tz2trmkf6xkuv8hr66mu0jqv889y5",
bitcoin_p2pkh_address: "mnXN3WkULtwtVf9VvzxvwXWYbdBSYvLDb7"
}
const privateKey = 'd2c1631c08d0aaafc642a0a53f314cf48554d0f9af2208310950b77b7c4dd6a701'
const publicKey = '03e0467426af5ab7b5e480e8d0501e288bb92f610cb45c7148420915219c3f6b13'
const sig100 = '0b659f27e35942363e8e6878ea3a0ea54a53faac03bfc9af3b7a46333081c2e84b5483df558c46e5263467e846d8fe337ef3ea467ae0e0d7066aada9857029bb01'
export const address = 'ST2ACZ7DAH6EH20V36ES9SJEERBX7VWGWV0YB91PG'
export const btcAddress = 'mu5o1rDdfP6g8NKa1RweQDo1zQT58KWjdR'

export function signMessageDirect(message: string) {
const privK = createStacksPrivateKey(keyChainTM.private_key)
//const utf8Bytes = utf8ToBytes('0xdeadbeef')

const arr = new Uint8Array([0xde, 0xad, 0xbe, 0xef])

const hash = sha256(arr);
//const hash = hashMessage(message); //hashMessage(message, '');
console.log('hash: ' + hex.encode(hash))
return {
signature: signMessageHashRsv({ privateKey: privK, messageHash: bytesToHex(hash) }).data,
publicKey: publicKeyToString(getPublicKey(privK)),
};
}