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

Feat/153 bug fixes #155

Merged
merged 4 commits into from
Jun 22, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 15 additions & 20 deletions src/lib/bridge_api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
import { CONFIG } from '$lib/config';
import type { PeginRequestI, WrappedPSBT, AddressObject } from 'sbtc-bridge-lib'
import { hex, base64 } from '@scure/base';
import type { Transaction } from '@scure/btc-signer'
import * as secp from '@noble/secp256k1';
import * as btc from '@scure/btc-signer';
//import { toStorable, getStacksAddressFromSignature } from 'sbtc-bridge-lib'
import { toStorable } from 'sbtc-bridge-lib'
import { verifyMessageSignatureRsv } from '@stacks/encryption';
import { hashMessage } from '@stacks/encryption';
import { recoverSignature } from "micro-stacks/connect";
import { c32address } from 'c32check';
import { sha256 } from '@noble/hashes/sha256';
import { ripemd160 } from '@noble/hashes/ripemd160';

function addNetSelector (path:string) {
if (CONFIG.VITE_NETWORK === 'testnet' || CONFIG.VITE_NETWORK === 'devnet') {
Expand Down Expand Up @@ -146,8 +134,8 @@ export async function savePeginCommit(peginRequest:PeginRequestI):Promise<any> {
if (response.status !== 200) {
console.log('Bitcoin address not known - is the network correct?');
}
const signedPsbt = await extractResponse(response);
return signedPsbt;
const res = await extractResponse(response);
return res;
}
export async function updatePeginCommit(peginRequest:PeginRequestI):Promise<any> { //<PeginRequestI|{insertedId:string; acknowledged:boolean;}> {
const path = addNetSelector(CONFIG.VITE_BRIDGE_API + '/sbtc/pegins');
Expand Down Expand Up @@ -194,6 +182,17 @@ export async function fetchPegins():Promise<Array<PeginRequestI>> {
return pegins;
}

export async function fetchCommitments(btcAddress:string, stxAddress:string, sbtcWalletAddress:string, revealFee:number):Promise<Array<PeginRequestI>> {
const path = addNetSelector(CONFIG.VITE_BRIDGE_API + '/sbtc/commit-scan/' + btcAddress + '/' + stxAddress + '/' + sbtcWalletAddress + '/' + revealFee);
const response = await fetchCatchErrors(path);
if (response.status !== 200) {
console.log('Request failed to url: ' + path);
return [];
}
const pegins = await extractResponse(response);
return pegins;
}

export async function fetchPeginsByStacksAddress(stxAddress:string):Promise<Array<PeginRequestI>> {
const path = addNetSelector(CONFIG.VITE_BRIDGE_API + '/sbtc/pegins/search/' + stxAddress);
const response = await fetchCatchErrors(path);
Expand Down Expand Up @@ -293,12 +292,8 @@ export async function fetchUserSbtcBalance(stxAddress:string) {
}
}
export async function fetchUserBalances(adrds:AddressObject) {
const path = addNetSelector(CONFIG.VITE_BRIDGE_API + '/sbtc/address/balances');
const response = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(adrds)
});
const path = addNetSelector(CONFIG.VITE_BRIDGE_API + '/sbtc/address/balances/' + adrds.stxAddress + '/' + adrds.cardinal + '/' + adrds.ordinal);
const response = await fetch(path);
if (response.status !== 200) {
console.log('Bitcoin address not known - is the network correct?');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { savePeginCommit } from '$lib/bridge_api';
import Button from '$lib/components/shared/Button.svelte';
import type { PeginRequestI } from 'sbtc-bridge-lib'
import CopyClipboard from '$lib/components/common/CopyClipboard.svelte';
import { makeFlash } from "$lib/stacks_connect";
import { makeFlash, appDetails } from "$lib/stacks_connect";
import Invoice from '../Invoice.svelte';

export let piTx: PegInTransactionI|PegOutTransactionI;
Expand Down Expand Up @@ -53,10 +53,7 @@ export async function requestSignPsbt() {
console.log(currentTx);
openPsbtRequestPopup({
hex: currentTx,
appDetails: {
name: 'sBTC Bridge',
icon: window.location.origin + '/img/icon_sbtc.png',
},
appDetails: appDetails(),
onFinish(data:any) {
broadcastTransaction(data.hex);
},
Expand Down
10 changes: 7 additions & 3 deletions src/lib/components/transactions/CommittedDeposit.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@ const doSign = async (txtype:string, sigData:any, message:string, tx:Uint8Array)
depositId: peginRequest._id
}
wrappedPsbt = await sign(wrappedPsbt);
if (wrappedPsbt.broadcastResult && wrappedPsbt.broadcastResult.failed) {
errorMessage = wrappedPsbt.broadcastResult.reason;
if (wrappedPsbt.broadcastResult) {
if (wrappedPsbt.broadcastResult.failed) {
errorMessage = wrappedPsbt.broadcastResult.reason;
} else if (wrappedPsbt.broadcastResult.error) {
errorMessage = 'Commitment transaction is not yet confirmed.. try again in 60 minutes.' //wrappedPsbt.broadcastResult.error;
}
}
if (typeof wrappedPsbt.signedTransaction === 'string') {
console.log('hex: ', wrappedPsbt.signedTransaction)
Expand Down Expand Up @@ -120,7 +124,7 @@ onMount(async () => {
Thanks for <a href={explorerBtcTxUrl(peginRequest.btcTxid)} target="_blank" rel="noreferrer" class={a_primary}>depositing</a> Bitcoin.
</p>
<p class="">
Your sBTC will materialise in your Stacks Web Wallet within 24 hours - if not you can use the reclaim button above to get your bitcoin sent back to your Web Wallet.
Your sBTC will materialise in your Stacks Web Wallet within 24 hours - if not you can <a href="/" class={a_primary} on:keyup on:click|preventDefault={() => reclaiming = !reclaiming}>reclaim</a> your bitcoin and have it sent back to your Web Wallet.
The <a class={a_primary} href="https://stacks.org" target="_blank">Stacks Foundation</a> maintains a list of accredited projects where you can put your sBTC to work.
</p>
<p class="">
Expand Down
2 changes: 1 addition & 1 deletion src/lib/domain/ReclaimOrRevealTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default class ReclaimOrRevealTransaction {
scureFee = 0;

public constructor(commitTx:PeginRequestI) {
(commitTx.sbtcWalletAddress.startsWith('tb')) ? this.net = btc.TEST_NETWORK : this.net = btc.NETWORK;
(commitTx?.sbtcWalletAddress?.startsWith('tb')) ? this.net = btc.TEST_NETWORK : this.net = btc.NETWORK;
this.commitTx = commitTx;
}

Expand Down
18 changes: 1 addition & 17 deletions src/lib/sbtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,6 @@ export const defaultSbtcConfig:SbtcConfig = {
debugMode: false,
testAddresses: false
},
peginRequest: {
_id: undefined,
originator: '',
status: 0,
tries: undefined,
updated: undefined,
amount: 0,
mode: '',
requestType: '',
wallet: undefined,
btcTxid: undefined,
fromBtcAddress: '',
stacksAddress: '',
sbtcWalletAddress: '',
commitTxScript: undefined,
vout: undefined
}
innerWidth: 1000
}

12 changes: 7 additions & 5 deletions src/lib/stacks_connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,11 @@ export function addresses():AddressObject {
}
}

export const appDetails = {
name: 'sBTC Bridge',
icon: window.location.origin + '/img/icon_sbtc.png',
export function appDetails() {
return {
name: 'sBTC Bridge',
icon: (window) ? window.location.origin + '/img/icon_sbtc.png' : '/img/icon_sbtc.png',
}
}

export function makeFlash(el1:HTMLElement|null) {
Expand Down Expand Up @@ -158,7 +160,7 @@ export async function loginStacksJs(callback:any):Promise<any> {
if (!userSession.isUserSignedIn()) {
showConnect({
userSession,
appDetails,
appDetails: appDetails(),
onFinish: async () => {
await fetchSbtcBalance();
callback(true);
Expand All @@ -181,7 +183,7 @@ export function signMessage(callback:any, script:string) {
openSignatureRequestPopup({
message: script,
network: getStacksNetwork(), // for mainnet, `new StacksMainnet()`
appDetails: appDetails,
appDetails: appDetails(),
onFinish(value) {
console.log('Signature of the message', value.signature);
console.log('Use public key:', value.publicKey);
Expand Down
4 changes: 2 additions & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
provides a non-custodial, permissionless way to move Bitcoin into and out of the Stacks Blockchain.
</p>
<p class="mb-2">
The Bridge provides features to build and track Bitcoin and Stacks transactions: it doesn't take
The Bridge interacts with Bitcoin and Stacks Blockchains: it does not take
custody of your money.
</p>
<p class="mb-2">
Expand All @@ -32,7 +32,7 @@
<Icon src="{ArrowSmallRight}" mini class="-mr-0.5 h-5 w-5" aria-hidden="true" />
</a>

<a href="/how-it-works" class="inline-flex items-center gap-x-1.5 bg-transparent px-4 py-2 font-normal text-white rounded-xl border border-transparent hover:bg-white/[8%] focus:bg-white/[16%] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-500/50" role="button">
<a href="/faq" class="inline-flex items-center gap-x-1.5 bg-transparent px-4 py-2 font-normal text-white rounded-xl border border-transparent hover:bg-white/[8%] focus:bg-white/[16%] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-500/50" role="button">
Learn more
</a>
</div>
Expand Down
3 changes: 3 additions & 0 deletions src/routes/transactions/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ const fetchDeposits = async (mine:boolean) => {
} else {
peginRequests = await fetchPegins()
}
// note this end point recovers the status 2 commitments from bitcoin - using the cardinal to find utxo's.
//peginRequests = await fetchCommitments($sbtcConfig?.addressObject?.cardinal!, $sbtcConfig?.addressObject?.stxAddress!, $sbtcConfig?.sbtcContractData.sbtcWalletAddress!, 5000)

peginRequests.sort(compare)
}

Expand Down
3 changes: 1 addition & 2 deletions src/types/sbtc_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ export type SbtcConfig = {
stxAddress?: string;
sigData:any;
pegIn:boolean;
peginRequest:PeginRequestI;
peginRequest?:PeginRequestI;
userSettings:SbtcUserSettingI;
sbtcContractData: SbtcContractDataI;
keys: KeySet;
sbtcAddressInfo: any;
innerWidth:number;
};

Expand Down
21 changes: 11 additions & 10 deletions tests/pegin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,38 +270,39 @@ describe('suite', () => {
const myPeg:PegInTransactionI = await PegInTransaction.hydrate(JSON.parse(JSON.stringify(pegin1)));
myPeg.net = btc.NETWORK;
const data = myPeg.buildData(addrM, false);
expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(5);
expect(parseInt(hex.encode(data.slice(4,5)), 16)).equals(22);
expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(22);
//expect(parseInt(hex.encode(data.slice(4,5)), 16)).equals(22);
})

it.concurrent('PegInTransaction.buildData() data built stacks testnet address', async () => {
const myPeg:PegInTransactionI = await PegInTransaction.hydrate(JSON.parse(JSON.stringify(pegin1)));
myPeg.net = btc.TEST_NETWORK;
const data = myPeg.buildData(addr, false);
expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(5);
expect(parseInt(hex.encode(data.slice(4,5)), 16)).equals(26);
expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(26);
//expect(parseInt(hex.encode(data.slice(4,5)), 16)).equals(26);
})

it.concurrent('PegInTransaction.buildData() can recover full stacks testnet from data built', async () => {
const myPeg:PegInTransactionI = await PegInTransaction.hydrate(JSON.parse(JSON.stringify(pegin1)));
myPeg.net = btc.TEST_NETWORK;
const data = myPeg.buildData(addr, false);

expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(5);
expect(parseInt(hex.encode(data.slice(4,5)), 16)).equals(26);
expect(parseInt(hex.encode(data.slice(3,4)), 16)).equals(26);

const addr0Buf = hex.encode(data.slice(4,5));
const addr1Buf = hex.encode(data.slice(5, 25));
const addr0Buf = hex.encode(data.slice(3,4));
const addr1Buf = hex.encode(data.slice(4, 24));
const address = c32address(parseInt(addr0Buf, 16), addr1Buf)
expect(address).equals(addr);
})

it.concurrent('PegInTransaction.buildData() can recover full stacks mainnet from data built', async () => {
const myPeg:PegInTransactionI = await PegInTransaction.hydrate(JSON.parse(JSON.stringify(pegin1)));
myPeg.net = btc.NETWORK;
console.log(myPeg.pegInData)
const data = myPeg.buildData(addrM, false);
const addr0Buf = hex.encode(data.slice(4,5));
const addr1Buf = hex.encode(data.slice(5, 25));
console.log('PegInTransaction.buildData() can recover full stacks mainnet from data built:' + hex.encode(data))
const addr0Buf = hex.encode(data.slice(3,4));
const addr1Buf = hex.encode(data.slice(4, 24));
const address = c32address(parseInt(addr0Buf, 16), addr1Buf)
expect(address).equals(addrM);
})
Expand Down
3 changes: 0 additions & 3 deletions tests/pegout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import type { PegOutTransactionI } from '$lib/domain/PegOutTransaction';
import { fail } from 'assert';
import { pegout1 } from './data/data_pegout_p2wpkh'
import { sha256 } from '@noble/hashes/sha256';
import { concatByteArrays } from '$lib/structured-data.js'
import { MAGIC_BYTES_TESTNET, MAGIC_BYTES_MAINNET, PEGOUT_OPCODE } from 'sbtc-bridge-lib'
import { uint8ToAmount, amountToUint8 } from 'sbtc-bridge-lib'

Expand Down Expand Up @@ -219,8 +218,6 @@ describe('suite', () => {
//amtBuf.writeUInt32LE(2500, 0);
//const amt = new Uint8Array(view.buffer)
const amt = amountToUint8(2500, 9)
const data = concatByteArrays([b1, amt])
expect(data.length).equals(b1.length + amt.length)

//const data = Buffer.concat([b1, amtBuf]);
//console.log('amtBuf: ' + (hex.encode(amt)))
Expand Down
37 changes: 0 additions & 37 deletions tests/structured_data.test.ts

This file was deleted.