Merge branch 'main' into diagon-alley

This commit is contained in:
ben 2022-09-21 16:25:52 +01:00
commit 71d643260c
31 changed files with 2568 additions and 140 deletions

View file

@ -1,6 +1,7 @@
FROM python:3.9-slim
RUN apt-get clean
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y curl pkg-config build-essential
RUN curl -sSL https://install.python-poetry.org | python3 -
ENV PATH="/root/.local/bin:$PATH"
WORKDIR /app

View file

@ -12,6 +12,8 @@ By default, LNbits will use SQLite as its database. You can also use PostgreSQL
## Option 1 (recommended): poetry
If you have problems installing LNbits using these instructions, please have a look at the [Troubleshooting](#troubleshooting) section.
```sh
git clone https://github.com/lnbits/lnbits-legend.git
cd lnbits-legend/
@ -26,12 +28,11 @@ curl -sSL https://install.python-poetry.org | python3 -
export PATH="/home/ubuntu/.local/bin:$PATH" # or whatever is suggested in the poetry install notes printed to terminal
poetry env use python3.9
poetry install --no-dev
poetry run python build.py
mkdir data
cp .env.example .env
sudo nano .env # set funding source
nano .env # set funding source
```
#### Running the server
@ -176,13 +177,15 @@ Problems installing? These commands have helped us install LNbits.
```sh
sudo apt install pkg-config libffi-dev libpq-dev
# build essentials for debian/ubuntu
sudo apt install python3.9-dev gcc build-essential
# if the secp256k1 build fails:
# if you used venv
./venv/bin/pip install setuptools wheel
# if you used poetry
poetry add setuptools wheel
# build essentials for debian/ubuntu
sudo apt install python3-dev gcc build-essential
# if you used venv
./venv/bin/pip install setuptools wheel
```
### Optional: PostgreSQL database

View file

@ -452,6 +452,15 @@ async def delete_payment(checking_id: str, conn: Optional[Connection] = None) ->
)
async def delete_wallet_payment(
checking_id: str, wallet_id: str, conn: Optional[Connection] = None
) -> None:
await (conn or db).execute(
"DELETE FROM apipayments WHERE checking_id = ? AND wallet = ?",
(checking_id, wallet_id),
)
async def check_internal(
payment_hash: str, conn: Optional[Connection] = None
) -> Optional[str]:

View file

@ -174,7 +174,7 @@ class Payment(BaseModel):
logger.warning(
f"Deleting outgoing failed payment {self.checking_id}: {status}"
)
await self.delete()
await self.delete(conn)
elif not status.pending:
logger.info(
f"Marking '{'in' if self.is_in else 'out'}' {self.checking_id} as not pending anymore: {status}"
@ -182,10 +182,10 @@ class Payment(BaseModel):
await self.update_status(status, conn=conn)
return status
async def delete(self) -> None:
async def delete(self, conn: Optional[Connection] = None) -> None:
from .crud import delete_payment
await delete_payment(self.checking_id)
await delete_payment(self.checking_id, conn=conn)
class BalanceCheck(BaseModel):

View file

@ -28,7 +28,7 @@ from . import db
from .crud import (
check_internal,
create_payment,
delete_payment,
delete_wallet_payment,
get_wallet,
get_wallet_payment,
update_payment_details,
@ -221,7 +221,7 @@ async def pay_invoice(
logger.warning(f"backend sent payment failure")
async with db.connect() as conn:
logger.debug(f"deleting temporary payment {temp_id}")
await delete_payment(temp_id, conn=conn)
await delete_wallet_payment(temp_id, wallet_id, conn=conn)
raise PaymentFailure(
f"payment failed: {payment.error_message}"
or "payment failed, but backend didn't give us an error message"

View file

@ -369,9 +369,9 @@ new Vue({
decodeRequest: function () {
this.parse.show = true
let req = this.parse.data.request.toLowerCase()
if (this.parse.data.request.startsWith('lightning:')) {
if (this.parse.data.request.toLowerCase().startsWith('lightning:')) {
this.parse.data.request = this.parse.data.request.slice(10)
} else if (this.parse.data.request.startsWith('lnurl:')) {
} else if (this.parse.data.request.toLowerCase().startsWith('lnurl:')) {
this.parse.data.request = this.parse.data.request.slice(6)
} else if (req.indexOf('lightning=lnurl1') !== -1) {
this.parse.data.request = this.parse.data.request

View file

@ -711,7 +711,7 @@
<q-card class="q-pa-lg">
<h6 class="q-my-md text-primary">Warning</h6>
<p>
Login functionality to be released in v0.2, for now,
Login functionality to be released in a future update, for now,
<strong
>make sure you bookmark this page for future access to your
wallet</strong

View file

@ -153,14 +153,18 @@ async def get_key_type(
LNBITS_ADMIN_USERS and wallet.wallet.user not in LNBITS_ADMIN_USERS
) and (LNBITS_ADMIN_EXTENSIONS and pathname in LNBITS_ADMIN_EXTENSIONS):
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED, detail="User not authorized."
status_code=HTTPStatus.FORBIDDEN,
detail="User not authorized for this extension.",
)
return wallet
except HTTPException as e:
if e.status_code == HTTPStatus.BAD_REQUEST:
raise
if e.status_code == HTTPStatus.UNAUTHORIZED:
elif e.status_code == HTTPStatus.UNAUTHORIZED:
# we pass this in case it is not an invoice key, nor an admin key, and then return NOT_FOUND at the end of this block
pass
else:
raise
except:
raise
raise HTTPException(

View file

@ -19,26 +19,9 @@ async def create_ticket(
(payment_hash, wallet, event, name, email, False, True),
)
ticket = await get_ticket(payment_hash)
assert ticket, "Newly created ticket couldn't be retrieved"
return ticket
async def set_ticket_paid(payment_hash: str) -> Tickets:
row = await db.fetchone("SELECT * FROM events.ticket WHERE id = ?", (payment_hash,))
if row[6] != True:
await db.execute(
"""
UPDATE events.ticket
SET paid = true
WHERE id = ?
""",
(payment_hash,),
)
eventdata = await get_event(row[2])
# UPDATE EVENT DATA ON SOLD TICKET
eventdata = await get_event(event)
assert eventdata, "Couldn't get event from ticket being paid"
sold = eventdata.sold + 1
amount_tickets = eventdata.amount_tickets - 1
await db.execute(
@ -47,11 +30,11 @@ async def set_ticket_paid(payment_hash: str) -> Tickets:
SET sold = ?, amount_tickets = ?
WHERE id = ?
""",
(sold, amount_tickets, row[2]),
(sold, amount_tickets, event),
)
ticket = await get_ticket(payment_hash)
assert ticket, "Newly updated ticket couldn't be retrieved"
assert ticket, "Newly created ticket couldn't be retrieved"
return ticket

View file

@ -24,7 +24,6 @@ from .crud import (
get_ticket,
get_tickets,
reg_ticket,
set_ticket_paid,
update_event,
)

View file

@ -5,13 +5,13 @@ animals = [
"duck",
"eagle",
"flamingo",
"gorila",
"gorilla",
"hamster",
"iguana",
"jaguar",
"koala",
"llama",
"macaroni penguim",
"macaroni penguin",
"numbat",
"octopus",
"platypus",

View file

@ -138,8 +138,9 @@
hide-dropdown-icon
input-debounce="0"
new-value-mode="add-unique"
label="Tip % Options"
></q-select>
label="Tip % Options (hit enter to add values)"
><q-tooltip>Hit enter to add values</q-tooltip></q-select
>
<div class="row q-mt-lg">
<q-btn
unelevated

View file

@ -253,7 +253,7 @@
name="check"
transition-show="fade"
class="text-light-green"
style="font-size: 40em"
style="font-size: min(90vw, 40em)"
></q-icon>
</q-dialog>
</q-page>
@ -294,6 +294,7 @@
exchangeRate: null,
stack: [],
tipAmount: 0.0,
hasNFC: false,
nfcTagReading: false,
invoiceDialog: {
show: false,
@ -370,7 +371,7 @@
this.showInvoice()
},
submitForm: function () {
if (this.tip_options.length) {
if (this.tip_options && this.tip_options.length) {
this.showTipModal()
} else {
this.showInvoice()
@ -413,9 +414,6 @@
dialog.show = false
self.complete.show = true
setTimeout(function () {
self.complete.show = false
}, 5000)
}
})
}, 3000)

View file

@ -23,9 +23,10 @@ async def create_watch_wallet(w: WalletAccount) -> WalletAccount:
type,
address_no,
balance,
network
network,
meta
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
wallet_id,
@ -37,6 +38,7 @@ async def create_watch_wallet(w: WalletAccount) -> WalletAccount:
w.address_no,
w.balance,
w.network,
w.meta,
),
)

View file

@ -93,3 +93,10 @@ async def m006_drop_mempool_table(db):
Mempool data is now part of `config`
"""
await db.execute("DROP TABLE watchonly.mempool;")
async def m007_add_wallet_meta_data(db):
"""
Add 'meta' for storing various metadata about the wallet
"""
await db.execute("ALTER TABLE watchonly.wallets ADD COLUMN meta TEXT DEFAULT '{}';")

View file

@ -9,6 +9,7 @@ class CreateWallet(BaseModel):
masterpub: str = Query("")
title: str = Query("")
network: str = "Mainnet"
meta: str = "{}"
class WalletAccount(BaseModel):
@ -21,6 +22,7 @@ class WalletAccount(BaseModel):
balance: int
type: Optional[str] = ""
network: str = "Mainnet"
meta: str = "{}"
@classmethod
def from_row(cls, row: Row) -> "WalletAccount":

View file

@ -104,6 +104,18 @@ async function payment(path) {
})
return
}
const p2trUtxo = this.utxos.find(
u => u.selected && u.accountType === 'p2tr'
)
if (p2trUtxo) {
this.$q.notify({
type: 'warning',
message: 'Taproot Signing not supported yet!',
caption: 'Please manually deselect the Taproot UTXOs',
timeout: 10000
})
return
}
if (!this.serialSignerRef.isAuthenticated()) {
await this.serialSignerRef.hwwShowPasswordDialog()
const authenticated = await this.serialSignerRef.isAuthenticating()

View file

@ -0,0 +1,80 @@
<div>
<div v-if="done">
<div class="row">
<div class="col-12">Seed Input Done</div>
</div>
</div>
<div v-else>
<div class="row">
<div class="col-3 q-pt-sm">Word Count</div>
<div class="col-6 q-pr-lg">
<q-select
filled
dense
v-model="wordCount"
type="number"
label="Word Count"
:options="wordCountOptions"
@input="initWords"
></q-select>
</div>
<div class="col-3 q-pr-lg"></div>
</div>
<div class="row">
<div class="col-3 q-pr-lg"></div>
<div class="col-6">Enter word at position: {{actualPosition}}</div>
<div class="col-3 q-pr-lg"></div>
</div>
<div class="row">
<div class="col-3 q-pr-lg">
<q-btn
v-if="currentPosition > 0"
@click="previousPosition"
unelevated
class="btn-full"
color="secondary"
>Previous</q-btn
>
</div>
<div class="col-6 q-pr-lg">
<q-select
filled
dense
use-input
hide-selected
fill-input
input-debounce="0"
v-model="currentWord"
:options="options"
@filter="filterFn"
@input-value="setModel"
></q-select>
</div>
<div class="col-3 q-pr-lg">
<q-btn
v-if="currentPosition < wordCount - 1"
@click="nextPosition"
unelevated
class="btn-full"
color="secondary"
>Next</q-btn
>
<q-btn
v-else
@click="seedInputDone"
unelevated
class="btn-full"
color="primary"
>Done</q-btn
>
</div>
<q-linear-progress
:value="currentPosition / (wordCount -1)"
size="5px"
color="primary"
class="q-mt-sm"
></q-linear-progress>
</div>
</div>
</div>

View file

@ -0,0 +1,102 @@
async function seedInput(path) {
const template = await loadTemplateAsync(path)
Vue.component('seed-input', {
name: 'seed-input',
template,
computed: {
actualPosition: function () {
return this.words[this.currentPosition].position
}
},
data: function () {
return {
wordCountOptions: ['12', '15', '18', '21', '24'],
wordCount: 24,
words: [],
currentPosition: 0,
stringOptions: [],
options: [],
currentWord: '',
done: false
}
},
methods: {
filterFn(val, update, abort) {
update(() => {
const needle = val.toLocaleLowerCase()
this.options = this.stringOptions
.filter(v => v.toLocaleLowerCase().indexOf(needle) != -1)
.sort((a, b) => {
if (a.startsWith(needle)) {
if (b.startsWith(needle)) {
return a - b
}
return -1
} else {
if (b.startsWith(needle)) {
return 1
}
return a - b
}
})
})
},
initWords() {
const words = []
for (let i = 1; i <= this.wordCount; i++) {
words.push({
position: i,
value: ''
})
}
this.currentPosition = 0
this.words = _.shuffle(words)
},
setModel(val) {
this.currentWord = val
this.words[this.currentPosition].value = this.currentWord
},
nextPosition() {
if (this.currentPosition < this.wordCount - 1) {
this.currentPosition++
}
this.currentWord = this.words[this.currentPosition].value
},
previousPosition() {
if (this.currentPosition > 0) {
this.currentPosition--
}
this.currentWord = this.words[this.currentPosition].value
},
seedInputDone() {
const badWordPositions = this.words
.filter(w => !w.value || !this.stringOptions.includes(w.value))
.map(w => w.position)
if (badWordPositions.length) {
this.$q.notify({
timeout: 10000,
type: 'warning',
message:
'The seed has incorrect words. Please check at these positions: ',
caption: 'Position: ' + badWordPositions.join(', ')
})
return
}
const mnemonic = this.words
.sort((a, b) => a.position - b.position)
.map(w => w.value)
.join(' ')
this.$emit('on-seed-input-done', mnemonic)
this.done = true
}
},
created: async function () {
this.stringOptions = bip39WordList
this.initWords()
}
})
}

View file

@ -170,6 +170,31 @@
type="password"
label="Password"
></q-input>
<q-separator></q-separator>
<q-toggle
label="Passphrase (optional)"
color="secodary"
v-model="hww.hasPassphrase"
></q-toggle>
<q-input
v-if="hww.hasPassphrase"
v-model.trim="hww.passphrase"
filled
:type="hww.showPassphrase ? 'text' : 'password'"
filled
dense
label="Passphrase"
>
<template v-slot:append>
<q-icon
:name="hww.showPassphrase ? 'visibility' : 'visibility_off'"
class="cursor-pointer"
@click="hww.showPassphrase = !hww.showPassphrase"
/>
</template>
</q-input>
<br />
<div class="row q-mt-lg">
<q-btn
@ -351,6 +376,18 @@
<q-dialog v-model="showConsole" position="top">
<q-card class="q-pa-lg q-pt-xl">
<div class="row q-mt-lg q-mb-lg">
<div class="col">
<q-badge
class="text-subtitle2 float-right"
color="yellow"
text-color="black"
>
Open the browser Developer Console for more Details!
</q-badge>
</div>
</div>
<q-input
filled
dense
@ -361,16 +398,29 @@
cols="200"
label="Console"
></q-input>
<div class="row q-mt-lg">
<q-btn v-close-popup flat color="grey" class="q-ml-auto">Close</q-btn>
</div>
</q-card>
</q-dialog>
<q-dialog v-model="hww.showSeedDialog" position="top">
<q-dialog v-model="hww.showSeedDialog" @hide="closeSeedDialog" position="top">
<q-card class="q-pa-lg q-pt-xl">
<span>Check word at position {{hww.seedWordPosition}} on display</span>
<span>Check word at position {{hww.seedWordPosition}} on device</span>
<div class="row q-mt-lg">
<div class="col-12">
<q-toggle
label="Show Seed Word"
color="secodary"
v-model="hww.showSeedWord"
></q-toggle>
</div>
</div>
<div v-if="hww.showSeedWord" class="row q-mt-lg">
<div class="col-12">
<q-input readonly v-model.trim="hww.seedWord"></q-input>
</div>
</div>
<div class="row q-mt-lg">
<div class="col-4">
@ -409,8 +459,15 @@
>
For test purposes only. Do not enter word list with real funds!!!
</q-badge>
<br /><br /><br />
<span>Enter new word list separated by space</span>
<br />
<q-toggle
label="Enter word list separated by space"
color="secodary"
v-model="hww.quickMnemonicInput"
></q-toggle>
<br />
<div v-if="hww.quickMnemonicInput">
<q-input
v-model.trim="hww.mnemonic"
filled
@ -427,30 +484,10 @@
/>
</template>
</q-input>
</div>
<seed-input v-else @on-seed-input-done="seedInputDone"></seed-input>
<br />
<q-toggle
label="Passphrase (optional)"
color="secodary"
v-model="hww.hasPassphrase"
></q-toggle>
<br />
<q-input
v-if="hww.hasPassphrase"
v-model.trim="hww.passphrase"
filled
:type="hww.showPassphrase ? 'text' : 'password'"
filled
dense
label="Passphrase"
>
<template v-slot:append>
<q-icon
:name="hww.showPassphrase ? 'visibility' : 'visibility_off'"
class="cursor-pointer"
@click="hww.showPassphrase = !hww.showPassphrase"
/>
</template>
</q-input>
<q-separator></q-separator>
<br />
<span>Enter new password (8 numbers/letters)</span>

View file

@ -22,6 +22,7 @@ async function serialSigner(path) {
showPassword: false,
mnemonic: null,
showMnemonic: false,
quickMnemonicInput: false,
passphrase: null,
showPassphrase: false,
hasPassphrase: false,
@ -38,6 +39,8 @@ async function serialSigner(path) {
psbtSentResolve: null,
xpubResolve: null,
seedWordPosition: 1,
seedWord: null,
showSeedWord: false,
showSeedDialog: false,
// config: null,
@ -172,6 +175,10 @@ async function serialSigner(path) {
isAuthenticated: function () {
return this.hww.authenticated
},
seedInputDone: function (mnemonic) {
this.hww.mnemonic = mnemonic
},
isAuthenticating: function () {
if (this.isAuthenticated()) return false
return new Promise(resolve => {
@ -374,6 +381,10 @@ async function serialSigner(path) {
})
}
},
closeSeedDialog: function () {
this.hww.seedWord = null
this.hww.showSeedWord = false
},
hwwConfirmNext: async function () {
this.hww.confirm.outputIndex += 1
if (this.hww.confirm.outputIndex >= this.tx.outputs.length) {
@ -403,7 +414,10 @@ async function serialSigner(path) {
},
hwwLogin: async function () {
try {
await this.sendCommandSecure(COMMAND_PASSWORD, [this.hww.password])
await this.sendCommandSecure(COMMAND_PASSWORD, [
this.hww.password,
this.hww.passphrase
])
} catch (error) {
this.$q.notify({
type: 'warning',
@ -414,7 +428,9 @@ async function serialSigner(path) {
} finally {
this.hww.showPasswordDialog = false
this.hww.password = null
this.hww.passphrase = null
this.hww.showPassword = false
this.hww.showPassphrase = false
}
},
handleLoginResponse: function (res = '') {
@ -449,6 +465,22 @@ async function serialSigner(path) {
})
}
},
hwwShowAddress: async function (path, address) {
try {
await this.sendCommandSecure(COMMAND_ADDRESS, [
this.network,
path,
address
])
} catch (error) {
this.$q.notify({
type: 'warning',
message: 'Failed to logout from Hardware Wallet!',
caption: `${error}`,
timeout: 10000
})
}
},
handleLogoutResponse: function (res = '') {
const authenticated = !(res.trim() === '1')
if (this.hww.authenticated && !authenticated) {
@ -796,21 +828,15 @@ async function serialSigner(path) {
await this.sendCommandSecure(COMMAND_SEED, [this.hww.seedWordPosition])
},
handleShowSeedResponse: function (res = '') {
const args = res.trim().split(' ')
const [pos, word] = res.trim().split(' ')
this.hww.seedWord = `${pos}. ${word}`
this.hww.seedWordPosition = pos
},
hwwRestore: async function () {
try {
let mnemonicWithPassphrase = this.hww.mnemonic
if (
this.hww.hasPassphrase &&
this.hww.passphrase &&
this.hww.passphrase.length
) {
mnemonicWithPassphrase += '/' + this.hww.passphrase
}
await this.sendCommandSecure(COMMAND_RESTORE, [
this.hww.password,
mnemonicWithPassphrase
this.hww.mnemonic
])
} catch (error) {
this.$q.notify({
@ -822,7 +848,6 @@ async function serialSigner(path) {
} finally {
this.hww.showRestoreDialog = false
this.hww.mnemonic = null
this.hww.passphrase = null
this.hww.showMnemonic = false
this.hww.password = null
this.hww.confirmedPassword = null

View file

@ -97,6 +97,13 @@
<q-badge v-if="props.row.isChange" color="orange" class="q-mr-md">
change
</q-badge>
<q-badge
v-if="props.row.accountType === 'p2tr'"
color="yellow"
text-color="black"
>
taproot
</q-badge>
</div>
</q-td>

View file

@ -116,6 +116,7 @@
>New Receive Address</q-btn
>
</div>
<div class="col-4">
{{getAccountDescription(props.row.type)}}
</div>
@ -124,15 +125,56 @@
<div class="row items-center no-wrap q-mb-md">
<div class="col-2 q-pr-lg">Master Pubkey:</div>
<div class="col-8">
<q-input
v-model="props.row.masterpub"
filled
readonly
type="textarea"
/>
<div class="col-7 q-pr-lg">
<q-input v-model="props.row.masterpub" filled readonly />
</div>
<div class="col-1">
<q-btn
unelevated
dense
size="md"
icon="qr_code"
:color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
@click="openQrCodeDialog(props.row.masterpub)"
></q-btn>
</div>
<div class="col-2 q-pr-lg">
<q-btn
outline
color="grey"
icon="content_copy"
@click="copyText(props.row.masterpub)"
class="q-ml-sm"
></q-btn>
</div>
</div>
<div
v-if="props.row.meta?.xpub"
class="row items-center no-wrap q-mb-md"
>
<div class="col-2 q-pr-lg">XPub:</div>
<div class="col-7 q-pr-lg">
<q-input v-model="props.row.meta.xpub" filled readonly />
</div>
<div class="col-1">
<q-btn
unelevated
dense
size="md"
icon="qr_code"
:color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
@click="openQrCodeDialog(props.row.meta.xpub)"
></q-btn>
</div>
<div class="col-2 q-pr-lg">
<q-btn
outline
color="grey"
icon="content_copy"
@click="copyText(props.row.meta.xpub)"
class="q-ml-sm"
></q-btn>
</div>
<div class="col-2 q-pr-lg"></div>
</div>
<div class="row items-center no-wrap q-mb-md">
<div class="col-2 q-pr-lg">Last Address Index:</div>
@ -229,4 +271,15 @@
</q-form>
</q-card>
</q-dialog>
<q-dialog v-model="showQrCodeDialog" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<q-responsive :ratio="1" class="q-mx-xl q-mb-md">
<qrcode
:value="qrCodeValue"
:options="{width: 800}"
class="rounded-borders"
></qrcode>
</q-responsive>
</q-card>
</q-dialog>
</div>

View file

@ -16,6 +16,8 @@ async function walletList(path) {
return {
walletAccounts: [],
address: {},
showQrCodeDialog: false,
qrCodeValue: null,
formDialog: {
show: false,
@ -118,9 +120,11 @@ async function walletList(path) {
},
createWalletAccount: async function (data) {
try {
const meta = {accountPath: this.accountPath}
if (this.formDialog.useSerialPort) {
const {xpub, fingerprint} = await this.fetchXpubFromHww()
if (!xpub) return
meta.xpub = xpub
const path = this.accountPath.substring(2)
const outputType = this.formDialog.addressType.id
if (outputType === 'sh') {
@ -129,6 +133,7 @@ async function walletList(path) {
data.masterpub = `${outputType}([${fingerprint}/${path}]${xpub}/{0,1}/*)`
}
}
data.meta = JSON.stringify(meta)
const response = await LNbits.api.request(
'POST',
'/watchonly/api/v1/wallet',
@ -233,7 +238,7 @@ async function walletList(path) {
const addressData = mapAddressesData(data)
addressData.note = `Shared on ${currentDateTime()}`
const lastAcctiveAddress =
const lastActiveAddress =
this.addresses
.filter(
a =>
@ -243,11 +248,11 @@ async function walletList(path) {
addressData.gapLimitExceeded =
!addressData.isChange &&
addressData.addressIndex >
lastAcctiveAddress.addressIndex + DEFAULT_RECEIVE_GAP_LIMIT
lastActiveAddress.addressIndex + DEFAULT_RECEIVE_GAP_LIMIT
const wallet = this.walletAccounts.find(w => w.id === walletId) || {}
wallet.address_no = addressData.addressIndex
this.$emit('new-receive-address', addressData)
this.$emit('new-receive-address', {addressData, wallet})
},
showAddAccountDialog: function () {
this.formDialog.show = true
@ -283,6 +288,20 @@ async function walletList(path) {
const addressType =
this.addressTypeOptions.find(t => t.id === value.id) || {}
this.accountPath = addressType[`path${this.network}`]
},
// todo: bad. base.js not present in custom components
copyText: function (text, message, position) {
var notify = this.$q.notify
Quasar.utils.copyToClipboard(text).then(function () {
notify({
message: message || 'Copied to clipboard!',
position: position || 'bottom'
})
})
},
openQrCodeDialog: function (qrCodeValue) {
this.qrCodeValue = qrCodeValue
this.showQrCodeDialog = true
}
},
created: async function () {

File diff suppressed because it is too large Load diff

View file

@ -7,6 +7,7 @@ const watchOnly = async () => {
await history('static/components/history/history.html')
await utxoList('static/components/utxo-list/utxo-list.html')
await feeRate('static/components/fee-rate/fee-rate.html')
await seedInput('static/components/seed-input/seed-input.html')
await sendTo('static/components/send-to/send-to.html')
await payment('static/components/payment/payment.html')
await serialSigner('static/components/serial-signer/serial-signer.html')
@ -172,10 +173,6 @@ const watchOnly = async () => {
this.$refs.paymentRef.updateSignedPsbt(psbtBase64)
},
//################### SERIAL PORT ###################
//################### HARDWARE WALLET ###################
//################### UTXOs ###################
scanAllAddresses: async function () {
await this.refreshAddresses()
@ -227,7 +224,7 @@ const watchOnly = async () => {
newAddr => !this.addresses.find(a => a.address === newAddr.address)
)
const lastAcctiveAddress =
const lastActiveAddress =
uniqueAddresses.filter(a => !a.isChange && a.hasActivity).pop() ||
{}
@ -237,7 +234,7 @@ const watchOnly = async () => {
a.gapLimitExceeded =
!a.isChange &&
a.addressIndex >
lastAcctiveAddress.addressIndex + DEFAULT_RECEIVE_GAP_LIMIT
lastActiveAddress.addressIndex + DEFAULT_RECEIVE_GAP_LIMIT
})
this.addresses.push(...uniqueAddresses)
}
@ -380,6 +377,26 @@ const watchOnly = async () => {
showAddressDetails: function (addressData) {
this.openQrCodeDialog(addressData)
},
showAddressDetailsWithConfirmation: function ({addressData, wallet}) {
this.showAddressDetails(addressData)
if (this.$refs.serialSigner.isConnected()) {
if (this.$refs.serialSigner.isAuthenticated()) {
if (wallet.meta?.accountPath) {
const branchIndex = addressData.isChange ? 1 : 0
const path =
wallet.meta.accountPath +
`/${branchIndex}/${addressData.addressIndex}`
this.$refs.serialSigner.hwwShowAddress(path, addressData.address)
}
} else {
this.$q.notify({
type: 'warning',
message: 'Please login in order to confirm address on device',
timeout: 10000
})
}
}
},
initUtxos: function (addresses) {
if (!this.fetchedUtxos && addresses.length) {
this.fetchedUtxos = true

View file

@ -74,6 +74,7 @@ const mapWalletAccount = function (o) {
'YYYY-MM-DD HH:mm'
)
: '',
meta: o.meta ? JSON.parse(o.meta) : null,
label: o.title,
expanded: false
})

View file

@ -3,6 +3,7 @@ const PSBT_BASE64_PREFIX = 'cHNidP8'
const COMMAND_PING = '/ping'
const COMMAND_PASSWORD = '/password'
const COMMAND_PASSWORD_CLEAR = '/password-clear'
const COMMAND_ADDRESS = '/address'
const COMMAND_SEND_PSBT = '/psbt'
const COMMAND_SIGN_PSBT = '/sign'
const COMMAND_HELP = '/help'

View file

@ -3,23 +3,36 @@
<p>
Onchain Wallet (watch-only) extension uses mempool.space<br />
For use with "account Extended Public Key"
<a href="https://iancoleman.io/bip39/">https://iancoleman.io/bip39/</a>
<a
href="https://iancoleman.io/bip39/"
target="_blank"
style="color: unset"
>https://iancoleman.io/bip39/</a
>
<br />
Flash binaries
<a
href="https://lnbits.github.io/hardware-wallet"
target="_blank"
style="color: unset"
>directly from browser</a
>
<small>
<br />Created by,
<a target="_blank" class="text-white" href="https://github.com/arcbtc"
<a target="_blank" style="color: unset" href="https://github.com/arcbtc"
>Ben Arc</a
>
(using,
<a
target="_blank"
class="text-white"
style="color: unset"
href="https://github.com/diybitcoinhardware/embit"
>Embit</a
></small
>)
<br />
<br />
<a target="_blank" href="/docs#/watchonly" class="text-white"
<a target="_blank" href="/docs#/watchonly" style="color: unset"
>Swagger REST API Documentation</a
>
</p>

View file

@ -27,7 +27,7 @@
:addresses="addresses"
:serial-signer-ref="$refs.serialSigner"
@accounts-update="updateAccounts"
@new-receive-address="showAddressDetails"
@new-receive-address="showAddressDetailsWithConfirmation"
>
</wallet-list>
@ -149,6 +149,7 @@
<q-card-section>
<h6 class="text-subtitle1 q-my-none">
{{SITE_TITLE}} Onchain Wallet (watch-only) Extension
<small>(v0.2)</small>
</h6>
</q-card-section>
<q-card-section class="q-pa-none">
@ -238,6 +239,8 @@
<script src="{{ url_for('watchonly_static', path='js/tables.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='js/map.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='js/utils.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='js/bip39-word-list.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/my-checkbox/my-checkbox.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/wallet-config/wallet-config.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/wallet-list/wallet-list.js') }}"></script>
@ -245,10 +248,12 @@
<script src="{{ url_for('watchonly_static', path='components/history/history.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/utxo-list/utxo-list.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/fee-rate/fee-rate.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/seed-input/seed-input.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/send-to/send-to.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/payment/payment.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/serial-signer/serial-signer.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='components/serial-port-config/serial-port-config.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='js/crypto/noble-secp256k1.js') }}"></script>
<script src="{{ url_for('watchonly_static', path='js/crypto/aes.js') }}"></script>

View file

@ -93,6 +93,7 @@ async def api_wallet_create_or_update(
address_no=-1, # so fresh address on empty wallet can get address with index 0
balance=0,
network=network["name"],
meta=data.meta,
)
wallets = await get_watch_wallets(w.wallet.user, network["name"])
@ -137,7 +138,7 @@ async def api_wallet_delete(wallet_id, w: WalletTypeInfo = Depends(require_admin
await delete_watch_wallet(wallet_id)
await delete_addresses_for_wallet(wallet_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
return "", HTTPStatus.NO_CONTENT
#############################ADDRESSES##########################
@ -268,7 +269,6 @@ async def api_psbt_create(
for i, inp in enumerate(inputs_extra):
psbt.inputs[i].bip32_derivations = inp["bip32_derivations"]
psbt.inputs[i].non_witness_utxo = inp.get("non_witness_utxo", None)
print("### ", inp.get("non_witness_utxo", None))
outputs_extra = []
bip32_derivations = {}
@ -343,11 +343,8 @@ async def api_tx_broadcast(
async with httpx.AsyncClient() as client:
r = await client.post(endpoint + "/api/tx", data=data.tx_hex)
tx_id = r.text
print("### broadcast tx_id: ", tx_id)
return tx_id
# return "0f0f0f0f0f0f0f0f0f0f0f00f0f0f0f0f0f0f0f0f0f00f0f0f0f0f0f0.mock.transaction.id"
except Exception as e:
print("### broadcast error: ", str(e))
raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))