diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9345706
--- /dev/null
+++ b/README.md
@@ -0,0 +1,88 @@
+# Bolt cards (NXP NTAG) Extension
+
+This extension allows you to link your Bolt Card (or other compatible NXP NTAG device) with a LNbits instance and use it in a more secure way than a static LNURLw. A technology called [Secure Unique NFC](https://mishka-scan.com/blog/secure-unique-nfc) is utilized in this workflow.
+
+Tutorial
+
+**Disclaimer:** ***Use this only if you either know what you are doing or are a reckless lightning pioneer. Only you are responsible for all your sats, cards and other devices. Always backup all your card keys!***
+
+
+***In order to use this extension you need to be able to setup your own card.*** That means writing a URL template pointing to your LNbits instance, configuring some SUN (SDM) settings and optionally changing the card's keys. There's a [guide](https://www.whitewolftech.com/articles/payment-card/) to set it up with a card reader connected to your computer. It can be done (without setting the keys) with [TagWriter app by NXP](https://play.google.com/store/apps/details?id=com.nxp.nfc.tagwriter) Android app. Last but not least, an OSS android app by name [Boltcard NFC Card Creator](https://github.com/boltcard/bolt-nfc-android-app) is being developed for these purposes. It's available from Google Play [here](https://play.google.com/store/apps/details?id=com.lightningnfcapp).
+
+## About the keys
+
+Up to five 16-byte keys can be stored on the card, numbered from 00 to 04. In the empty state they all should be set to zeros (00000000000000000000000000000000). For this extension only two keys need to be set, but for the security reasons all five keys should be changed from default (empty) state. The keys directly needed by this extension are:
+
+- One for encrypting the card UID and the counter (p parameter), let's called it meta key, key #01 or K1.
+
+- One for calculating CMAC (c parameter), let's called it file key, key #02 or K2.
+
+The key #00, K0 (also know as auth key) is used as authentification key. It is not directly needed by this extension, but should be filled in order to write the keys in cooperation with Boltcard NFC Card Creator. In this case also K3 is set to same value as K1 and K4 as K2, so all keys are changed from default values. Keep that in your mind in case you ever need to reset the keys manually.
+
+***Always backup all keys that you're trying to write on the card. Without them you may not be able to change them in the future!***
+
+
+## Setting the card - Boltcard NFC Card Creator (easy way)
+Updated for v0.1.3
+
+- Add new card in the extension.
+ - Set a max sats per transaction. Any transaction greater than this amount will be rejected.
+ - Set a max sats per day. After the card spends this amount of sats in a day, additional transactions will be rejected.
+ - Set a card name. This is just for your reference inside LNbits.
+ - Set the card UID. This is the unique identifier on your NFC card and is 7 bytes.
+ - If on an Android device with a newish version of Chrome, you can click the icon next to the input and tap your card to autofill this field.
+ - Otherwise read it with the Android app (Advanced -> Read NFC) and paste it to the field.
+ - Advanced Options
+ - Card Keys (k0, k1, k2) will be automatically generated if not explicitly set.
+ - Set to 16 bytes of 0s (00000000000000000000000000000000) to leave the keys in default (empty) state (this is unsecure).
+ - GENERATE KEY button fill the keys randomly.
+ - Click CREATE CARD button
+- Click the QR code button next to a card to view its details. Backup the keys now! They'll be comfortable in your password manager.
+ - Now you can scan the QR code with the Android app (Create Bolt Card -> SCAN QR CODE).
+ - Or you can Click the "KEYS / AUTH LINK" button to copy the auth URL to the clipboard. Then paste it into the Android app (Create Bolt Card -> PASTE AUTH URL).
+- Click WRITE CARD NOW and approach the NFC card to set it up. DO NOT REMOVE THE CARD PREMATURELY!
+
+## Erasing the card - Boltcard NFC Card Creator
+Updated for v0.1.3
+
+Since v0.1.2 of Boltcard NFC Card Creator it is possible not only reset the keys but also disable the SUN function and do the complete erase so the card can be use again as a static tag (or set as a new Bolt Card, ofc).
+
+- Click the QR code button next to a card to view its details and select WIPE
+- OR click the red cross icon on the right side to reach the same
+- In the android app (Advanced -> Reset Keys)
+ - Click SCAN QR CODE to scan the QR
+ - Or click WIPE DATA in LNbits to copy and paste in to the app (PASTE KEY JSON)
+- Click RESET CARD NOW and approach the NFC card to erase it. DO NOT REMOVE THE CARD PREMATURELY!
+- Now if there is all success the card can be safely delete from LNbits (but keep the keys backuped anyway; batter safe than brick).
+
+If you somehow find yourself in some non-standard state (for instance only k3 and k4 remains filled after previous unsuccessful reset), then you need edit the key fields manually (for instance leave k0-k2 to zeroes and provide the right k3 and k4).
+
+## Setting the card - computer (hard way)
+
+Follow the guide.
+
+The URI should be `lnurlw://YOUR-DOMAIN.COM/boltcards/api/v1/scan/{YOUR_card_external_id}?p=00000000000000000000000000000000&c=0000000000000000`
+
+Then fill up the card parameters in the extension. Card Auth key (K0) can be filled in the extension just for the record. Initical counter can be 0.
+
+## Setting the card - android NXP app (hard way)
+- If you don't know the card ID, use NXP TagInfo app to find it out.
+- In the TagWriter app tap Write tags
+- New Data Set > Link
+- Set URI type to Custom URL
+- URL should look like lnurlw://YOUR_LNBITS_DOMAIN/boltcards/api/v1/scan/{YOUR_card_external_id}?p=00000000000000000000000000000000&c=0000000000000000
+- click Configure mirroring options
+- Select Card Type NTAG 424 DNA
+- Check Enable SDM Mirroring
+- Select SDM Meta Read Access Right to 01
+- Check Enable UID Mirroring
+- Check Enable Counter Mirroring
+- Set SDM Counter Retrieval Key to 0E
+- Set PICC Data Offset to immediately after e=
+- Set Derivation Key for CMAC Calculation to 00
+- Set SDM MAC Input Offset to immediately after c=
+- Set SDM MAC Offset to immediately after c=
+- Save & Write
+- Scan with compatible Wallet
+
+This app afaik cannot change the keys. If you cannot change them any other way, leave them empty in the extension dialog and remember you're not secured. Card Auth key (K0) can be omitted anyway. Initical counter can be 0.
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000..5c6b87a
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,37 @@
+import asyncio
+
+from fastapi import APIRouter
+from starlette.staticfiles import StaticFiles
+
+from lnbits.db import Database
+from lnbits.helpers import template_renderer
+from lnbits.tasks import catch_everything_and_restart
+
+db = Database("ext_boltcards")
+
+boltcards_static_files = [
+ {
+ "path": "/boltcards/static",
+ "app": StaticFiles(packages=[("lnbits", "extensions/boltcards/static")]),
+ "name": "boltcards_static",
+ }
+]
+
+boltcards_ext: APIRouter = APIRouter(prefix="/boltcards", tags=["boltcards"])
+
+
+def boltcards_renderer():
+ return template_renderer(["lnbits/extensions/boltcards/templates"])
+
+
+from .lnurl import * # noqa: F401,F403
+from .tasks import * # noqa: F401,F403
+
+
+def boltcards_start():
+ loop = asyncio.get_event_loop()
+ loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) # noqa: F405
+
+
+from .views import * # noqa: F401,F403
+from .views_api import * # noqa: F401,F403
diff --git a/config.json b/config.json
new file mode 100644
index 0000000..0551f18
--- /dev/null
+++ b/config.json
@@ -0,0 +1,6 @@
+{
+ "name": "Bolt Cards",
+ "short_description": "Self custody Bolt Cards with one time LNURLw",
+ "tile": "/boltcards/static/image/boltcard.png",
+ "contributors": ["iwarpbtc", "arcbtc", "leesalminen"]
+}
diff --git a/crud.py b/crud.py
new file mode 100644
index 0000000..0a678e7
--- /dev/null
+++ b/crud.py
@@ -0,0 +1,278 @@
+import secrets
+from datetime import datetime
+from typing import List, Optional
+
+from lnbits.helpers import urlsafe_short_hash
+
+from . import db
+from .models import Card, CreateCardData, Hit, Refund
+
+
+async def create_card(data: CreateCardData, wallet_id: str) -> Card:
+ card_id = urlsafe_short_hash().upper()
+ extenal_id = urlsafe_short_hash().lower()
+
+ await db.execute(
+ """
+ INSERT INTO boltcards.cards (
+ id,
+ uid,
+ external_id,
+ wallet,
+ card_name,
+ counter,
+ tx_limit,
+ daily_limit,
+ enable,
+ k0,
+ k1,
+ k2,
+ otp
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ card_id,
+ data.uid.upper(),
+ extenal_id,
+ wallet_id,
+ data.card_name,
+ data.counter,
+ data.tx_limit,
+ data.daily_limit,
+ True,
+ data.k0,
+ data.k1,
+ data.k2,
+ secrets.token_hex(16),
+ ),
+ )
+ card = await get_card(card_id)
+ assert card, "Newly created card couldn't be retrieved"
+ return card
+
+
+async def update_card(card_id: str, **kwargs) -> Optional[Card]:
+ if "is_unique" in kwargs:
+ kwargs["is_unique"] = int(kwargs["is_unique"])
+ if "uid" in kwargs:
+ kwargs["uid"] = kwargs["uid"].upper()
+ q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
+ await db.execute(
+ f"UPDATE boltcards.cards SET {q} WHERE id = ?",
+ (*kwargs.values(), card_id),
+ )
+ row = await db.fetchone("SELECT * FROM boltcards.cards WHERE id = ?", (card_id,))
+ return Card(**row) if row else None
+
+
+async def get_cards(wallet_ids: List[str]) -> List[Card]:
+ if len(wallet_ids) == 0:
+ return []
+
+ q = ",".join(["?"] * len(wallet_ids))
+ rows = await db.fetchall(
+ f"SELECT * FROM boltcards.cards WHERE wallet IN ({q})", (*wallet_ids,)
+ )
+
+ return [Card(**row) for row in rows]
+
+
+async def get_card(card_id: str) -> Optional[Card]:
+ row = await db.fetchone("SELECT * FROM boltcards.cards WHERE id = ?", (card_id,))
+ if not row:
+ return None
+
+ card = dict(**row)
+
+ return Card.parse_obj(card)
+
+
+async def get_card_by_uid(card_uid: str) -> Optional[Card]:
+ row = await db.fetchone(
+ "SELECT * FROM boltcards.cards WHERE uid = ?", (card_uid.upper(),)
+ )
+ if not row:
+ return None
+
+ card = dict(**row)
+
+ return Card.parse_obj(card)
+
+
+async def get_card_by_external_id(external_id: str) -> Optional[Card]:
+ row = await db.fetchone(
+ "SELECT * FROM boltcards.cards WHERE external_id = ?", (external_id.lower(),)
+ )
+ if not row:
+ return None
+
+ card = dict(**row)
+
+ return Card.parse_obj(card)
+
+
+async def get_card_by_otp(otp: str) -> Optional[Card]:
+ row = await db.fetchone("SELECT * FROM boltcards.cards WHERE otp = ?", (otp,))
+ if not row:
+ return None
+
+ card = dict(**row)
+
+ return Card.parse_obj(card)
+
+
+async def delete_card(card_id: str) -> None:
+ # Delete cards
+ await db.execute("DELETE FROM boltcards.cards WHERE id = ?", (card_id,))
+ # Delete hits
+ hits = await get_hits([card_id])
+ for hit in hits:
+ await db.execute("DELETE FROM boltcards.hits WHERE id = ?", (hit.id,))
+ # Delete refunds
+ refunds = await get_refunds([hit.id])
+ for refund in refunds:
+ await db.execute(
+ "DELETE FROM boltcards.refunds WHERE id = ?", (refund.hit_id,)
+ )
+
+
+async def update_card_counter(counter: int, id: str):
+ await db.execute(
+ "UPDATE boltcards.cards SET counter = ? WHERE id = ?",
+ (counter, id),
+ )
+
+
+async def enable_disable_card(enable: bool, id: str) -> Optional[Card]:
+ await db.execute(
+ "UPDATE boltcards.cards SET enable = ? WHERE id = ?",
+ (enable, id),
+ )
+ return await get_card(id)
+
+
+async def update_card_otp(otp: str, id: str):
+ await db.execute(
+ "UPDATE boltcards.cards SET otp = ? WHERE id = ?",
+ (otp, id),
+ )
+
+
+async def get_hit(hit_id: str) -> Optional[Hit]:
+ row = await db.fetchone("SELECT * FROM boltcards.hits WHERE id = ?", (hit_id,))
+ if not row:
+ return None
+
+ hit = dict(**row)
+
+ return Hit.parse_obj(hit)
+
+
+async def get_hits(cards_ids: List[str]) -> List[Hit]:
+ if len(cards_ids) == 0:
+ return []
+
+ q = ",".join(["?"] * len(cards_ids))
+ rows = await db.fetchall(
+ f"SELECT * FROM boltcards.hits WHERE card_id IN ({q})", (*cards_ids,)
+ )
+
+ return [Hit(**row) for row in rows]
+
+
+async def get_hits_today(card_id: str) -> List[Hit]:
+ rows = await db.fetchall(
+ "SELECT * FROM boltcards.hits WHERE card_id = ?",
+ (card_id,),
+ )
+ updatedrow = []
+ for row in rows:
+ if datetime.now().date() == datetime.fromtimestamp(row.time).date():
+ updatedrow.append(row)
+
+ return [Hit(**row) for row in updatedrow]
+
+
+async def spend_hit(id: str, amount: int):
+ await db.execute(
+ "UPDATE boltcards.hits SET spent = ?, amount = ? WHERE id = ?",
+ (True, amount, id),
+ )
+ return await get_hit(id)
+
+
+async def create_hit(card_id, ip, useragent, old_ctr, new_ctr) -> Hit:
+ hit_id = urlsafe_short_hash()
+ await db.execute(
+ """
+ INSERT INTO boltcards.hits (
+ id,
+ card_id,
+ ip,
+ spent,
+ useragent,
+ old_ctr,
+ new_ctr,
+ amount
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ hit_id,
+ card_id,
+ ip,
+ False,
+ useragent,
+ old_ctr,
+ new_ctr,
+ 0,
+ ),
+ )
+ hit = await get_hit(hit_id)
+ assert hit, "Newly recorded hit couldn't be retrieved"
+ return hit
+
+
+async def create_refund(hit_id, refund_amount) -> Refund:
+ refund_id = urlsafe_short_hash()
+ await db.execute(
+ """
+ INSERT INTO boltcards.refunds (
+ id,
+ hit_id,
+ refund_amount
+ )
+ VALUES (?, ?, ?)
+ """,
+ (
+ refund_id,
+ hit_id,
+ refund_amount,
+ ),
+ )
+ refund = await get_refund(refund_id)
+ assert refund, "Newly recorded hit couldn't be retrieved"
+ return refund
+
+
+async def get_refund(refund_id: str) -> Optional[Refund]:
+ row = await db.fetchone(
+ "SELECT * FROM boltcards.refunds WHERE id = ?", (refund_id,)
+ )
+ if not row:
+ return None
+ refund = dict(**row)
+ return Refund.parse_obj(refund)
+
+
+async def get_refunds(hits_ids: List[str]) -> List[Refund]:
+ if len(hits_ids) == 0:
+ return []
+
+ q = ",".join(["?"] * len(hits_ids))
+ rows = await db.fetchall(
+ f"SELECT * FROM boltcards.refunds WHERE hit_id IN ({q})", (*hits_ids,)
+ )
+
+ return [Refund(**row) for row in rows]
diff --git a/lnurl.py b/lnurl.py
new file mode 100644
index 0000000..3b99fdf
--- /dev/null
+++ b/lnurl.py
@@ -0,0 +1,222 @@
+import json
+import secrets
+from http import HTTPStatus
+from urllib.parse import urlparse
+
+from fastapi import HTTPException, Query, Request
+from lnurl import encode as lnurl_encode
+from lnurl.types import LnurlPayMetadata
+from starlette.responses import HTMLResponse
+
+from lnbits import bolt11
+from lnbits.core.services import create_invoice
+from lnbits.core.views.api import pay_invoice
+
+from . import boltcards_ext
+from .crud import (
+ create_hit,
+ get_card,
+ get_card_by_external_id,
+ get_card_by_otp,
+ get_hit,
+ get_hits_today,
+ spend_hit,
+ update_card_counter,
+ update_card_otp,
+)
+from .nxp424 import decryptSUN, getSunMAC
+
+###############LNURLWITHDRAW#################
+
+
+# /boltcards/api/v1/scan?p=00000000000000000000000000000000&c=0000000000000000
+@boltcards_ext.get("/api/v1/scan/{external_id}")
+async def api_scan(p, c, request: Request, external_id: str = Query(None)):
+ # some wallets send everything as lower case, no bueno
+ p = p.upper()
+ c = c.upper()
+ card = None
+ counter = b""
+ card = await get_card_by_external_id(external_id)
+ if not card:
+ return {"status": "ERROR", "reason": "No card."}
+ if not card.enable:
+ return {"status": "ERROR", "reason": "Card is disabled."}
+ try:
+ card_uid, counter = decryptSUN(bytes.fromhex(p), bytes.fromhex(card.k1))
+ if card.uid.upper() != card_uid.hex().upper():
+ return {"status": "ERROR", "reason": "Card UID mis-match."}
+ if c != getSunMAC(card_uid, counter, bytes.fromhex(card.k2)).hex().upper():
+ return {"status": "ERROR", "reason": "CMAC does not check."}
+ except:
+ return {"status": "ERROR", "reason": "Error decrypting card."}
+
+ ctr_int = int.from_bytes(counter, "little")
+
+ if ctr_int <= card.counter:
+ return {"status": "ERROR", "reason": "This link is already used."}
+
+ await update_card_counter(ctr_int, card.id)
+
+ # gathering some info for hit record
+ assert request.client
+ ip = request.client.host
+ if "x-real-ip" in request.headers:
+ ip = request.headers["x-real-ip"]
+ elif "x-forwarded-for" in request.headers:
+ ip = request.headers["x-forwarded-for"]
+
+ agent = request.headers["user-agent"] if "user-agent" in request.headers else ""
+ todays_hits = await get_hits_today(card.id)
+
+ hits_amount = 0
+ for hit in todays_hits:
+ hits_amount = hits_amount + hit.amount
+ if hits_amount > card.daily_limit:
+ return {"status": "ERROR", "reason": "Max daily limit spent."}
+ hit = await create_hit(card.id, ip, agent, card.counter, ctr_int)
+ lnurlpay = lnurl_encode(request.url_for("boltcards.lnurlp_response", hit_id=hit.id))
+ return {
+ "tag": "withdrawRequest",
+ "callback": request.url_for("boltcards.lnurl_callback", hitid=hit.id),
+ "k1": hit.id,
+ "minWithdrawable": 1 * 1000,
+ "maxWithdrawable": card.tx_limit * 1000,
+ "defaultDescription": f"Boltcard (refund address lnurl://{lnurlpay})",
+ }
+
+
+@boltcards_ext.get(
+ "/api/v1/lnurl/cb/{hitid}",
+ status_code=HTTPStatus.OK,
+ name="boltcards.lnurl_callback",
+)
+async def lnurl_callback(
+ pr: str = Query(None),
+ k1: str = Query(None),
+):
+ if not k1:
+ return {"status": "ERROR", "reason": "Missing K1 token"}
+
+ hit = await get_hit(k1)
+
+ if not hit:
+ return {
+ "status": "ERROR",
+ "reason": "Record not found for this charge (bad k1)",
+ }
+ if hit.spent:
+ return {"status": "ERROR", "reason": "Payment already claimed"}
+ if not pr:
+ return {"status": "ERROR", "reason": "Missing payment request"}
+
+ try:
+ invoice = bolt11.decode(pr)
+ except:
+ return {"status": "ERROR", "reason": "Failed to decode payment request"}
+
+ card = await get_card(hit.card_id)
+ assert card
+ hit = await spend_hit(id=hit.id, amount=int(invoice.amount_msat / 1000))
+ assert hit
+ try:
+ await pay_invoice(
+ wallet_id=card.wallet,
+ payment_request=pr,
+ max_sat=card.tx_limit,
+ extra={"tag": "boltcard", "hit": hit.id},
+ )
+ return {"status": "OK"}
+ except Exception as exc:
+ return {"status": "ERROR", "reason": f"Payment failed - {exc}"}
+
+
+# /boltcards/api/v1/auth?a=00000000000000000000000000000000
+@boltcards_ext.get("/api/v1/auth")
+async def api_auth(a, request: Request):
+ if a == "00000000000000000000000000000000":
+ response = {"k0": "0" * 32, "k1": "1" * 32, "k2": "2" * 32}
+ return response
+
+ card = await get_card_by_otp(a)
+ if not card:
+ raise HTTPException(
+ detail="Card does not exist.", status_code=HTTPStatus.NOT_FOUND
+ )
+
+ new_otp = secrets.token_hex(16)
+ await update_card_otp(new_otp, card.id)
+
+ lnurlw_base = (
+ f"{urlparse(str(request.url)).netloc}/boltcards/api/v1/scan/{card.external_id}"
+ )
+
+ response = {
+ "card_name": card.card_name,
+ "id": str(1),
+ "k0": card.k0,
+ "k1": card.k1,
+ "k2": card.k2,
+ "k3": card.k1,
+ "k4": card.k2,
+ "lnurlw_base": "lnurlw://" + lnurlw_base,
+ "protocol_name": "new_bolt_card_response",
+ "protocol_version": str(1),
+ }
+
+ return response
+
+
+###############LNURLPAY REFUNDS#################
+
+
+@boltcards_ext.get(
+ "/api/v1/lnurlp/{hit_id}",
+ response_class=HTMLResponse,
+ name="boltcards.lnurlp_response",
+)
+async def lnurlp_response(req: Request, hit_id: str = Query(None)):
+ hit = await get_hit(hit_id)
+ assert hit
+ card = await get_card(hit.card_id)
+ assert card
+ if not hit:
+ return {"status": "ERROR", "reason": "LNURL-pay record not found."}
+ if not card.enable:
+ return {"status": "ERROR", "reason": "Card is disabled."}
+ payResponse = {
+ "tag": "payRequest",
+ "callback": req.url_for("boltcards.lnurlp_callback", hit_id=hit_id),
+ "metadata": LnurlPayMetadata(json.dumps([["text/plain", "Refund"]])),
+ "minSendable": 1 * 1000,
+ "maxSendable": card.tx_limit * 1000,
+ }
+ return json.dumps(payResponse)
+
+
+@boltcards_ext.get(
+ "/api/v1/lnurlp/cb/{hit_id}",
+ response_class=HTMLResponse,
+ name="boltcards.lnurlp_callback",
+)
+async def lnurlp_callback(hit_id: str = Query(None), amount: str = Query(None)):
+ hit = await get_hit(hit_id)
+ assert hit
+ card = await get_card(hit.card_id)
+ assert card
+ if not hit:
+ return {"status": "ERROR", "reason": "LNURL-pay record not found."}
+
+ _, payment_request = await create_invoice(
+ wallet_id=card.wallet,
+ amount=int(int(amount) / 1000),
+ memo=f"Refund {hit_id}",
+ unhashed_description=LnurlPayMetadata(
+ json.dumps([["text/plain", "Refund"]])
+ ).encode(),
+ extra={"refund": hit_id},
+ )
+
+ payResponse = {"pr": payment_request, "routes": []}
+
+ return json.dumps(payResponse)
diff --git a/migrations.py b/migrations.py
new file mode 100644
index 0000000..43d5bb0
--- /dev/null
+++ b/migrations.py
@@ -0,0 +1,57 @@
+async def m001_initial(db):
+ await db.execute(
+ """
+ CREATE TABLE boltcards.cards (
+ id TEXT PRIMARY KEY UNIQUE,
+ wallet TEXT NOT NULL,
+ card_name TEXT NOT NULL,
+ uid TEXT NOT NULL UNIQUE,
+ external_id TEXT NOT NULL UNIQUE,
+ counter INT NOT NULL DEFAULT 0,
+ tx_limit TEXT NOT NULL,
+ daily_limit TEXT NOT NULL,
+ enable BOOL NOT NULL,
+ k0 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ k1 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ k2 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ prev_k0 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ prev_k1 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ prev_k2 TEXT NOT NULL DEFAULT '00000000000000000000000000000000',
+ otp TEXT NOT NULL DEFAULT '',
+ time TIMESTAMP NOT NULL DEFAULT """
+ + db.timestamp_now
+ + """
+ );
+ """
+ )
+
+ await db.execute(
+ f"""
+ CREATE TABLE boltcards.hits (
+ id TEXT PRIMARY KEY UNIQUE,
+ card_id TEXT NOT NULL,
+ ip TEXT NOT NULL,
+ spent BOOL NOT NULL DEFAULT True,
+ useragent TEXT,
+ old_ctr INT NOT NULL DEFAULT 0,
+ new_ctr INT NOT NULL DEFAULT 0,
+ amount {db.big_int} NOT NULL,
+ time TIMESTAMP NOT NULL DEFAULT """
+ + db.timestamp_now
+ + """
+ );
+ """
+ )
+
+ await db.execute(
+ f"""
+ CREATE TABLE boltcards.refunds (
+ id TEXT PRIMARY KEY UNIQUE,
+ hit_id TEXT NOT NULL,
+ refund_amount {db.big_int} NOT NULL,
+ time TIMESTAMP NOT NULL DEFAULT """
+ + db.timestamp_now
+ + """
+ );
+ """
+ )
diff --git a/models.py b/models.py
new file mode 100644
index 0000000..5ea4be1
--- /dev/null
+++ b/models.py
@@ -0,0 +1,83 @@
+import json
+from sqlite3 import Row
+
+from fastapi import Query, Request
+from lnurl import Lnurl
+from lnurl import encode as lnurl_encode
+from lnurl.types import LnurlPayMetadata
+from pydantic import BaseModel
+
+ZERO_KEY = "00000000000000000000000000000000"
+
+
+class Card(BaseModel):
+ id: str
+ wallet: str
+ card_name: str
+ uid: str
+ external_id: str
+ counter: int
+ tx_limit: int
+ daily_limit: int
+ enable: bool
+ k0: str
+ k1: str
+ k2: str
+ prev_k0: str
+ prev_k1: str
+ prev_k2: str
+ otp: str
+ time: int
+
+ @classmethod
+ def from_row(cls, row: Row) -> "Card":
+ return cls(**dict(row))
+
+ def lnurl(self, req: Request) -> Lnurl:
+ url = req.url_for("boltcard.lnurl_response", device_id=self.id, _external=True)
+ return lnurl_encode(url)
+
+ async def lnurlpay_metadata(self) -> LnurlPayMetadata:
+ return LnurlPayMetadata(json.dumps([["text/plain", self.card_name]]))
+
+
+class CreateCardData(BaseModel):
+ card_name: str = Query(...)
+ uid: str = Query(...)
+ counter: int = Query(0)
+ tx_limit: int = Query(0)
+ daily_limit: int = Query(0)
+ enable: bool = Query(True)
+ k0: str = Query(ZERO_KEY)
+ k1: str = Query(ZERO_KEY)
+ k2: str = Query(ZERO_KEY)
+ prev_k0: str = Query(ZERO_KEY)
+ prev_k1: str = Query(ZERO_KEY)
+ prev_k2: str = Query(ZERO_KEY)
+
+
+class Hit(BaseModel):
+ id: str
+ card_id: str
+ ip: str
+ spent: bool
+ useragent: str
+ old_ctr: int
+ new_ctr: int
+ amount: int
+ time: int
+
+ @classmethod
+ def from_row(cls, row: Row) -> "Hit":
+ return cls(**dict(row))
+
+
+class Refund(BaseModel):
+ id: str
+ hit_id: str
+ refund_amount: int
+ time: int
+
+ @classmethod
+ def from_row(cls, row: Row) -> "Refund":
+ return cls(**dict(row))
diff --git a/nxp424.py b/nxp424.py
new file mode 100644
index 0000000..83f4e50
--- /dev/null
+++ b/nxp424.py
@@ -0,0 +1,36 @@
+# https://www.nxp.com/docs/en/application-note/AN12196.pdf
+from typing import Tuple
+
+from Cryptodome.Cipher import AES
+from Cryptodome.Hash import CMAC
+
+SV2 = "3CC300010080"
+
+
+def myCMAC(key: bytes, msg: bytes = b"") -> bytes:
+ cobj = CMAC.new(key, ciphermod=AES)
+ if msg != b"":
+ cobj.update(msg)
+ return cobj.digest()
+
+
+def decryptSUN(sun: bytes, key: bytes) -> Tuple[bytes, bytes]:
+ IVbytes = b"\x00" * 16
+
+ cipher = AES.new(key, AES.MODE_CBC, IVbytes)
+ sun_plain = cipher.decrypt(sun)
+
+ UID = sun_plain[1:8]
+ counter = sun_plain[8:11]
+
+ return UID, counter
+
+
+def getSunMAC(UID: bytes, counter: bytes, key: bytes) -> bytes:
+ sv2prefix = bytes.fromhex(SV2)
+ sv2bytes = sv2prefix + UID + counter
+
+ mac1 = myCMAC(key, sv2bytes)
+ mac2 = myCMAC(mac1)
+
+ return mac2[1::2]
diff --git a/static/image/boltcard.png b/static/image/boltcard.png
new file mode 100644
index 0000000..ce79906
Binary files /dev/null and b/static/image/boltcard.png differ
diff --git a/static/js/index.js b/static/js/index.js
new file mode 100644
index 0000000..880a555
--- /dev/null
+++ b/static/js/index.js
@@ -0,0 +1,456 @@
+Vue.component(VueQrcode.name, VueQrcode)
+
+const mapCards = obj => {
+ obj.date = Quasar.utils.date.formatDate(
+ new Date(obj.time * 1000),
+ 'YYYY-MM-DD HH:mm'
+ )
+
+ return obj
+}
+
+new Vue({
+ el: '#vue',
+ mixins: [windowMixin],
+ data: function () {
+ return {
+ toggleAdvanced: false,
+ nfcTagReading: false,
+ lnurlLink: `${window.location.host}/boltcards/api/v1/scan/`,
+ cards: [],
+ hits: [],
+ refunds: [],
+ cardDialog: {
+ show: false,
+ data: {
+ counter: 1,
+ k0: '',
+ k1: '',
+ k2: '',
+ uid: '',
+ card_name: ''
+ },
+ temp: {}
+ },
+ cardsTable: {
+ columns: [
+ {
+ name: 'card_name',
+ align: 'left',
+ label: 'Card name',
+ field: 'card_name'
+ },
+ {
+ name: 'counter',
+ align: 'left',
+ label: 'Counter',
+ field: 'counter'
+ },
+ {
+ name: 'wallet',
+ align: 'left',
+ label: 'Wallet',
+ field: 'wallet'
+ },
+ {
+ name: 'tx_limit',
+ align: 'left',
+ label: 'Max tx',
+ field: 'tx_limit'
+ },
+ {
+ name: 'daily_limit',
+ align: 'left',
+ label: 'Daily tx limit',
+ field: 'daily_limit'
+ }
+ ],
+ pagination: {
+ rowsPerPage: 10
+ }
+ },
+ refundsTable: {
+ columns: [
+ {
+ name: 'hit_id',
+ align: 'left',
+ label: 'Hit ID',
+ field: 'hit_id'
+ },
+ {
+ name: 'refund_amount',
+ align: 'left',
+ label: 'Refund Amount',
+ field: 'refund_amount'
+ },
+ {
+ name: 'date',
+ align: 'left',
+ label: 'Time',
+ field: 'date'
+ }
+ ],
+ pagination: {
+ rowsPerPage: 10,
+ sortBy: 'date',
+ descending: true
+ }
+ },
+ hitsTable: {
+ columns: [
+ {
+ name: 'card_name',
+ align: 'left',
+ label: 'Card name',
+ field: 'card_name'
+ },
+ {
+ name: 'amount',
+ align: 'left',
+ label: 'Amount',
+ field: 'amount'
+ },
+ {
+ name: 'old_ctr',
+ align: 'left',
+ label: 'Old counter',
+ field: 'old_ctr'
+ },
+ {
+ name: 'new_ctr',
+ align: 'left',
+ label: 'New counter',
+ field: 'new_ctr'
+ },
+ {
+ name: 'date',
+ align: 'left',
+ label: 'Time',
+ field: 'date'
+ },
+ {
+ name: 'ip',
+ align: 'left',
+ label: 'IP',
+ field: 'ip'
+ },
+ {
+ name: 'useragent',
+ align: 'left',
+ label: 'User agent',
+ field: 'useragent'
+ }
+ ],
+ pagination: {
+ rowsPerPage: 10,
+ sortBy: 'date',
+ descending: true
+ }
+ },
+ qrCodeDialog: {
+ show: false,
+ wipe: false,
+ data: null
+ }
+ }
+ },
+ methods: {
+ readNfcTag: function () {
+ try {
+ const self = this
+
+ if (typeof NDEFReader == 'undefined') {
+ throw {
+ toString: function () {
+ return 'NFC not supported on this device or browser.'
+ }
+ }
+ }
+
+ const ndef = new NDEFReader()
+
+ const readerAbortController = new AbortController()
+ readerAbortController.signal.onabort = event => {
+ console.log('All NFC Read operations have been aborted.')
+ }
+
+ this.nfcTagReading = true
+ this.$q.notify({
+ message: 'Tap your NFC tag to copy its UID here.'
+ })
+
+ return ndef.scan({signal: readerAbortController.signal}).then(() => {
+ ndef.onreadingerror = () => {
+ self.nfcTagReading = false
+
+ this.$q.notify({
+ type: 'negative',
+ message: 'There was an error reading this NFC tag.'
+ })
+
+ readerAbortController.abort()
+ }
+
+ ndef.onreading = ({message, serialNumber}) => {
+ //Decode NDEF data from tag
+ var self = this
+ self.cardDialog.data.uid = serialNumber
+ .toUpperCase()
+ .replaceAll(':', '')
+ this.$q.notify({
+ type: 'positive',
+ message: 'NFC tag read successfully.'
+ })
+ }
+ })
+ } catch (error) {
+ this.nfcTagReading = false
+ this.$q.notify({
+ type: 'negative',
+ message: error
+ ? error.toString()
+ : 'An unexpected error has occurred.'
+ })
+ }
+ },
+ getCards: function () {
+ var self = this
+
+ LNbits.api
+ .request(
+ 'GET',
+ '/boltcards/api/v1/cards?all_wallets=true',
+ this.g.user.wallets[0].inkey
+ )
+ .then(function (response) {
+ self.cards = response.data.map(function (obj) {
+ return mapCards(obj)
+ })
+ })
+ .then(function () {
+ self.getHits()
+ })
+ },
+ getHits: function () {
+ var self = this
+ LNbits.api
+ .request(
+ 'GET',
+ '/boltcards/api/v1/hits?all_wallets=true',
+ this.g.user.wallets[0].inkey
+ )
+ .then(function (response) {
+ self.hits = response.data.map(function (obj) {
+ obj.card_name = self.cards.find(d => d.id == obj.card_id).card_name
+ return mapCards(obj)
+ })
+ })
+ },
+ getRefunds: function () {
+ var self = this
+ LNbits.api
+ .request(
+ 'GET',
+ '/boltcards/api/v1/refunds?all_wallets=true',
+ this.g.user.wallets[0].inkey
+ )
+ .then(function (response) {
+ self.refunds = response.data.map(function (obj) {
+ return mapCards(obj)
+ })
+ })
+ },
+ openQrCodeDialog(cardId, wipe) {
+ var card = _.findWhere(this.cards, {id: cardId})
+ this.qrCodeDialog.data = {
+ id: card.id,
+ link: window.location.origin + '/boltcards/api/v1/auth?a=' + card.otp,
+ name: card.card_name,
+ uid: card.uid,
+ external_id: card.external_id,
+ k0: card.k0,
+ k1: card.k1,
+ k2: card.k2,
+ k3: card.k1,
+ k4: card.k2
+ }
+ this.qrCodeDialog.data_wipe = JSON.stringify({
+ action: 'wipe',
+ k0: card.k0,
+ k1: card.k1,
+ k2: card.k2,
+ k3: card.k1,
+ k4: card.k2,
+ uid: card.uid,
+ version: 1
+ })
+ this.qrCodeDialog.wipe = wipe
+ this.qrCodeDialog.show = true
+ },
+ addCardOpen: function () {
+ this.cardDialog.show = true
+ this.generateKeys()
+ },
+ generateKeys: function () {
+ var self = this
+ const genRanHex = size =>
+ [...Array(size)]
+ .map(() => Math.floor(Math.random() * 16).toString(16))
+ .join('')
+
+ debugcard =
+ typeof this.cardDialog.data.card_name === 'string' &&
+ this.cardDialog.data.card_name.search('debug') > -1
+
+ self.cardDialog.data.k0 = debugcard
+ ? '11111111111111111111111111111111'
+ : genRanHex(32)
+
+ self.cardDialog.data.k1 = debugcard
+ ? '22222222222222222222222222222222'
+ : genRanHex(32)
+
+ self.cardDialog.data.k2 = debugcard
+ ? '33333333333333333333333333333333'
+ : genRanHex(32)
+ },
+ closeFormDialog: function () {
+ this.cardDialog.data = {}
+ },
+ sendFormData: function () {
+ let wallet = _.findWhere(this.g.user.wallets, {
+ id: this.cardDialog.data.wallet
+ })
+ let data = this.cardDialog.data
+ if (data.id) {
+ this.updateCard(wallet, data)
+ } else {
+ this.createCard(wallet, data)
+ }
+ },
+ createCard: function (wallet, data) {
+ var self = this
+
+ LNbits.api
+ .request('POST', '/boltcards/api/v1/cards', wallet.adminkey, data)
+ .then(function (response) {
+ self.cards.push(mapCards(response.data))
+ self.cardDialog.show = false
+ self.cardDialog.data = {}
+ })
+ .catch(function (error) {
+ LNbits.utils.notifyApiError(error)
+ })
+ },
+ updateCardDialog: function (formId) {
+ var card = _.findWhere(this.cards, {id: formId})
+ this.cardDialog.data = _.clone(card)
+
+ this.cardDialog.temp.k0 = this.cardDialog.data.k0
+ this.cardDialog.temp.k1 = this.cardDialog.data.k1
+ this.cardDialog.temp.k2 = this.cardDialog.data.k2
+
+ this.cardDialog.show = true
+ },
+ updateCard: function (wallet, data) {
+ var self = this
+
+ if (
+ this.cardDialog.temp.k0 != data.k0 ||
+ this.cardDialog.temp.k1 != data.k1 ||
+ this.cardDialog.temp.k2 != data.k2
+ ) {
+ data.prev_k0 = this.cardDialog.temp.k0
+ data.prev_k1 = this.cardDialog.temp.k1
+ data.prev_k2 = this.cardDialog.temp.k2
+ }
+
+ LNbits.api
+ .request(
+ 'PUT',
+ '/boltcards/api/v1/cards/' + data.id,
+ wallet.adminkey,
+ data
+ )
+ .then(function (response) {
+ self.cards = _.reject(self.cards, function (obj) {
+ return obj.id == data.id
+ })
+ self.cards.push(mapCards(response.data))
+ self.cardDialog.show = false
+ self.cardDialog.data = {}
+ })
+ .catch(function (error) {
+ LNbits.utils.notifyApiError(error)
+ })
+ },
+ enableCard: function (wallet, card_id, enable) {
+ var self = this
+ let fullWallet = _.findWhere(self.g.user.wallets, {
+ id: wallet
+ })
+ LNbits.api
+ .request(
+ 'GET',
+ '/boltcards/api/v1/cards/enable/' + card_id + '/' + enable,
+ fullWallet.adminkey
+ )
+ .then(function (response) {
+ console.log(response.data)
+ self.cards = _.reject(self.cards, function (obj) {
+ return obj.id == response.data.id
+ })
+ self.cards.push(mapCards(response.data))
+ })
+ .catch(function (error) {
+ LNbits.utils.notifyApiError(error)
+ })
+ },
+ deleteCard: function (cardId) {
+ let self = this
+ let cards = _.findWhere(this.cards, {id: cardId})
+
+ Quasar.utils.exportFile(
+ cards.card_name + '.json',
+ this.qrCodeDialog.data_wipe,
+ 'application/json'
+ )
+
+ LNbits.utils
+ .confirmDialog(
+ "Are you sure you want to delete this card? Without access to the card keys you won't be able to reset them in the future!"
+ )
+ .onOk(function () {
+ LNbits.api
+ .request(
+ 'DELETE',
+ '/boltcards/api/v1/cards/' + cardId,
+ _.findWhere(self.g.user.wallets, {id: cards.wallet}).adminkey
+ )
+ .then(function (response) {
+ self.cards = _.reject(self.cards, function (obj) {
+ return obj.id == cardId
+ })
+ })
+ .catch(function (error) {
+ LNbits.utils.notifyApiError(error)
+ })
+ })
+ },
+ exportCardsCSV: function () {
+ LNbits.utils.exportCSV(this.cardsTable.columns, this.cards)
+ },
+ exportHitsCSV: function () {
+ LNbits.utils.exportCSV(this.hitsTable.columns, this.hits)
+ },
+ exportRefundsCSV: function () {
+ LNbits.utils.exportCSV(this.refundsTable.columns, this.refunds)
+ }
+ },
+ created: function () {
+ if (this.g.user.wallets.length) {
+ this.getCards()
+ this.getRefunds()
+ }
+ }
+})
diff --git a/tasks.py b/tasks.py
new file mode 100644
index 0000000..375e700
--- /dev/null
+++ b/tasks.py
@@ -0,0 +1,47 @@
+import asyncio
+import json
+
+from lnbits.core import db as core_db
+from lnbits.core.models import Payment
+from lnbits.helpers import get_current_extension_name
+from lnbits.tasks import register_invoice_listener
+
+from .crud import create_refund, get_hit
+
+
+async def wait_for_paid_invoices():
+ invoice_queue = asyncio.Queue()
+ register_invoice_listener(invoice_queue, get_current_extension_name())
+
+ while True:
+ payment = await invoice_queue.get()
+ await on_invoice_paid(payment)
+
+
+async def on_invoice_paid(payment: Payment) -> None:
+
+ if not payment.extra.get("refund"):
+ return
+
+ if payment.extra.get("wh_status"):
+ # this webhook has already been sent
+ return
+
+ hit = await get_hit(str(payment.extra.get("refund")))
+
+ if hit:
+ await create_refund(hit_id=hit.id, refund_amount=(payment.amount / 1000))
+ await mark_webhook_sent(payment, 1)
+
+
+async def mark_webhook_sent(payment: Payment, status: int) -> None:
+
+ payment.extra["wh_status"] = status
+
+ await core_db.execute(
+ """
+ UPDATE apipayments SET extra = ?
+ WHERE hash = ?
+ """,
+ (json.dumps(payment.extra), payment.payment_hash),
+ )
diff --git a/templates/boltcards/_api_docs.html b/templates/boltcards/_api_docs.html
new file mode 100644
index 0000000..ec5ed57
--- /dev/null
+++ b/templates/boltcards/_api_docs.html
@@ -0,0 +1,22 @@
+
+ Manage your Bolt Cards self custodian wayBe your own card association
+
+
+ More details
+
+
+ (QR for create the card in + Boltcard NFC Card Creator) +
++ (QR for wipe the card in + Boltcard NFC Card Creator) +
+
+ Name: {{ qrCodeDialog.data.name }}
+ UID: {{ qrCodeDialog.data.uid }}
+ External ID: {{ qrCodeDialog.data.external_id }}
+ Lock key (K0): {{ qrCodeDialog.data.k0 }}
+ Meta key (K1 & K3): {{ qrCodeDialog.data.k1 }}
+ File key (K2 & K4): {{ qrCodeDialog.data.k2 }}
+
+ Always backup all keys that you're trying to write on the card. Without + them you may not be able to change them in the future! +
+