Giter VIP home page Giter VIP logo

krux's Introduction

created at downloads downloads (latest release) commits (since latest release) codecov calver License: MIT

Krux is an open-source firmware facilitating the creation of Bitcoin signing devices from readily available components, such as Kendryte K210 devices. It transforms these devices into airgapped tools capable of handling transactions for both single and multisignature wallets, supporting offline signing via QR code or SD card, thus empowering users to securely self-custody their Bitcoin.


Disclaimer

WARNING: This software has not yet been formally audited by a third party. Use at your own risk!


Getting Started

Detailed instructions for installing and running Krux can now be found in our official documentation

The instructions below are intended for programmers or developers who want to contribute to the project.

Development

Fetch the code

This will download the source code of Krux as well as the code of all its dependencies inside a new folder called krux:

git clone --recurse-submodules https://github.com/selfcustody/krux

Note: When you wish to pull updates (to all submodules, their submodules, ...) to this repo, use:

git pull origin main && git submodule update --init --recursive

Krux (script) (Linux or WSL)

The krux bash script contains commands for common development tasks. It assumes a Linux host, you will need to have Docker Desktop or Docker Engine, openssl, and wget installed at a minimum for the commands to work as expected. It works on Windows using WSL. The channel Crypto Guide from Youtube made a step-by-step video - Krux DIY Bitcoin Signer: Build From Source & Verify (With Windows + WSL2 + Docker)

To build and flash the firmware:

# build firmware for Maix Amigo
./krux build maixpy_amigo

# flash the firmware to Maix Amigo
./krux flash maixpy_amigo

The first time, the build can take around an hour or so to complete. Subsequent builds should take only a few minutes. If all goes well, you should see a new build folder containing firmware.bin and kboot.kfpkg files when the build completes.

Install Krux and dev tools

Krux uses Poetry as Python packaging and dependency management. This cmd installs development dependencies like embit, ur and urtypes, and tools to run tests, review code with pylint, format code with black and a lib to help handle i18n translations.

pip install poetry
poetry install

If you have a problem installing Poetry on Linux OS:

# we considered the name of the venv .krux
python -m venv .krux
source .krux/bin/activate

The result will be something like:

(.krux) username:~/directory name$ 

Now you can run normaly the pip of the poetry:

pip install poetry
poetry install

Note: when changing the dependencies in pyptoject.toml you need to generate a new poetry.lock file using the cmd: poetry lock --no-update.

Format code

poetry run poe format

Review code

poetry run poe lint

Run tests with coverage

poetry run poe test

Note: The coverage report will be created at the htmlcov folder file:///path/to/krux/htmlcov/index.html.

For more verbose output (e.g., to see the output of print statements):

poetry run poe test-verbose

To run just a specific test from a specific file:

poetry run pytest --cache-clear ./tests/pages/test_login.py -k 'test_load_key_from_hexadecimal'

Use the Python interpreter (REPL)

This is useful for rapid development of non-visual code:

poetry run python
Python 3.9.1
Type "help", "copyright", "credits" or "license" for more information.
>>> from krux.key import Key
>>> Key("olympic term tissue route sense program under choose bean emerge velvet absurd", False).xpub()
'tpubDCDuqu5HtBX2aD7wxvnHcj1DgFN1UVgzLkA1Ms4Va4P7TpJ3jDknkPLwWT2SqrKXNNAtJBCPcbJ8Tcpm6nLxgFapCZyhKgqwcEGv1BVpD7s'
>>>

Run the device simulator

This is useful for rapid code development that utilizes UI/UX. It is also good for newcomers to try Krux before purchasing a device. However, the simulator does not behave exactly as the HW device and may not have all features implemented (e.g. scanning via camera a TinySeed currently only works on the HW device).

Before executing, make sure you have installed the poetry extras:

# This cmd will uninstall other extras
poetry install --extras simulator

# To install all extras, use:
poetry install --all-extras

Run the simulator:

# Run simulator with the touch device Amigo, then use mouse to navigate
poetry run poe simulator

# Run simulator with SD enabled (folder `simulator/sd`) on the small button-only device M5stickV, then use keyboard (arrow keys UP or DOWN and ENTER)
poetry run poe simulator-m5stickv --sd

# Run simulator on the device dock, then use keyboard (arrow keys UP or DOWN and ENTER)
poetry run poe simulator-dock

# Run simulator with the touch device yahboom, then use mouse to navigate
poetry run poe simulator-yahboom

# Run simulator on the device cube, then use keyboard (arrow keys UP or DOWN and ENTER)
poetry run poe simulator-cube

Note: With emulated SD card it is possible to store settings, encrypted mnemonics, also drop and sign PSBTs. After some time running, the simulator may become slow. If that happens, just close and open again!

# ImportError: Unable to find zbar shared library
sudo apt install python3-zbar

# ImportError: libGL.so.1: cannot open shared object file: No such file or directory
sudo apt install libgl1

# `pygame.error: No available video device`
# You are trying to run the simulator on an OS without a GUI (some kind of terminal only or WSL). Try one with GUI!

# Depending on the OS, it may be necessary to install zbar-tools too:
sudo apt install zbar-tools

Simulator sequences execution

This is useful for taking screenshots of device screens to use in documentation:

# Run all sequences of commands on all devices and in all locales (languages) [Linux OS]
cd simulator
./generate-all-screenshots.sh

# Run a specific sequence for a specific device's with SD enabled (folder `simulator/sd`)
poetry run poe simulator --sequence sequences/about.txt --sd

# Sequence screenshots are scaled to fit in docs. Use --no-screenshot-scale to get full size
poetry run poe simulator --sequence sequences/home-options.txt --no-screenshot-scale

Live debug a device (Linux)

It is not possible to drop into a live Python REPL anymore as we disabled the MICROPY_ENABLE_COMPILER flag in firmware\MaixPy\components\micropython\port\include\mpconfigport.h. If you enable it again it will be possible to drop into a live Python REPL by issuing an interrupt with Ctrl-C:

If you've made a fresh build and flashed it to your device, you can connect to the device over serial connection with:

screen /dev/tty.usbserial-device-name 115200

If successful, the device should restart and you should see:

K210 bootloader by LoBo v.1.4.1

* Find applications in MAIN parameters
0: '       firmware', @ 0x00080000, size=XXX, app_size=XXX, App ok, ACTIVE
* Loading app from flash at 0x00080000 (XXX B)
* Starting at 0x80000000 ...


[MAIXPY] Pll0:freq:XXX
[MAIXPY] Pll1:freq:XXX
[MAIXPY] Pll2:freq:XXX
[MAIXPY] cpu:freq:XXX
[MAIXPY] kpu:freq:XXX
[MAIXPY] Flash:0xef:0x17
[MaixPy] gc heap=0x8029f430-0x8036f430(851968)
init i2c:2 freq:XXX
[MAIXPY]: find ov7740
[MAIXPY]: find ov sensor

Some devices like Amigo have two serial ports, check the second one if you don't read data from first.

To leave screen serial monitor press Ctrl+a, followed by k, then confirm with y.

Live debug a device using MaixPy IDE (Mac or Windows)

Use MaixPy IDE to debug the devices. Click on Tools > Open Terminal > New Terminal > Connect to serial port > Select a COM port available (if didn't work, try another COM port). We have removed some support for MaixPy IDE (due to size constraints), but the debug works.

WDT watchdog

Krux makes use of MaixPy's WDT watchdog module, you can see it here. This will reset the device if not fed for some time. To stop the watchdog, when connected through the terminal, run the following:

# Run this everytime you want to stop the watchdog

from krux.wdt import wdt
wdt.stop()

# OR create this config to disable the watchdog, save the settings file and reset the device (in order to make krux read the new file!)

import json, machine

CONF_FILENAME="/flash/settings.json"
CONF_NAME="WATCHDOG_DISABLE"

conf_dict = {}
try:
  with open(CONF_FILENAME, "rb") as f:
    conf_dict = json.loads(f.read())
except:
    pass

conf_dict[CONF_NAME] = 1

with open(CONF_FILENAME, "w") as f:
    f.write(json.dumps(conf_dict))
    
machine.reset()

Now, with watchdog disabled, you can use debug the device normally. Also remember to disable the Settings > Security > Shutdown Time setting it to 0 to no more automatic resets, and if you added any print statements to the code, they should appear whenever your code is reached.

Traceback (most recent call last):
  File "_boot.py", line 109, in <module>
  File "_boot.py", line 64, in login
  File "krux/pages/__init__.py", line 498, in run
  File "krux/pages/__init__.py", line 614, in run_loop
  File "krux/input.py", line 325, in wait_for_button
  File "krux/input.py", line 238, in _wait_for_press
KeyboardInterrupt: 
MicroPython v1.11 on 2024-03-11; Sipeed_M1 with kendryte-k210
Type "help()" for more information.
>>> 
>>> 

Create new translations - i18n

The project has lots of translations here, if you add new english messages in code using t() function, you will need to:

# Clean unused translations:
poetry run poe i18n clean

# Create a new translation file in JSON:
poetry run poe i18n new tr-TR

# Use Google translate to create missing translations, copy them to respective files, review phrases and commas.
poetry run poe i18n fill

# Create missing translations for a single language. Ex: Brazilian Portuguese
poetry run poe i18n fill pt-BR

# Make sure all files have this new translated message:
poetry run poe i18n validate

# Format translation files properly:
poetry run poe i18n prettify

# Create the compiled table for krux translations.py
poetry run poe i18n bake

Fonts

Learn about how to setup fonts here

Colors

Use this script to generate device compatible colors from RGB values (usefull for color themes).

Documentation

Before change documentation, and run the mkdocs server, make sure you have installed the poetry extras:

# This cmd will uninstall other extras
poetry install --extras docs

# To install all extras, use:
poetry install --all-extras

To change lateral and upper menus on documentation, see mkdocs.yml file on nav section. To create or edit translations (TODO: need help!), read here.

Create the documentation site locally - http://127.0.0.1:8000/krux/:

poetry run poe docs

Inspired by these similar projects

Powered by

  • embit, a Bitcoin library for Python 3 and Micropython
  • MaixPy, MicroPython for K210 RISC-V
  • MicroPython, a lean and efficient Python implementation for microcontrollers and constrained systems
  • Kboot and ktool

Contributing

Issues and pull requests welcome! Let's make this as good as it can be.

Feel free to start a new discussion or an issue for work. When making your pull request, explain what it solves, ideally each PR should focus on solving one issue (exceptions can be made if the work is related or tightly coupled).

Note for PR's: Checkout and branch off of the develop branch, please also make sure to explicitly target develop; main is the default branch for the latest version and also for downloading and installing Krux from source.

Support

For technical support installing or using Krux, you can join our Telegram chat. Follow us on X (Twitter) or send a message to the Bitcoin Forum. Also check out the DIYbitcoin chat on Telegram, a broader community of tinkerers, builders and hackers!

Please do not use issues for support requests. If necessary, you can use our Discussions to post your question here on GitHub.

krux's People

Contributors

aglkm avatar bancagaming avatar bavarianledger avatar hugoender avatar johngtrs avatar kkdao avatar odudex avatar plebbitor avatar pmk avatar qlrd avatar satfrog avatar selose avatar stepansnigirev avatar tadeubas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

krux's Issues

Set up CI/CD

There are a few things that should be run for every PR:

  • pylint (on the src, fonts, and i18n directories): This is currently 10/10, and I want to keep it that way
  • python i18n/i18n.py validate: This makes sure all translations are complete
  • Tests: Have to write these...
  • firmware build to make sure it doesn't get broken

On merge, mkdocs build will need to be run to keep the documentation site up to date.

I'll also need to write a script to cut releases, building firmware for every locale and signing them.

github permission errors

hello and great looking project!

when i try to run the first command on a linux OS i get many git@github permission denied errors when it tries to clone each submodule.

when i searched what to do it suggests creating an SSH key for my github account, but i don't understand what that has to do with your repo - apologies for my ignorance!

Testing on Manjaro OS vs MacOS

I tried to get through the commands on the Manjaro OS and it was fine for building and flashing, but with the microSD section and the ./krux flash-software /Volumes/SD command, it does not copy over the necessary files properly. The contents are the same as what is in the Krux directory.

When I try with MacOS it copies over the necessary python files and directories, and this time when the microSD is loaded into the device it boots successfully.

I have not tested with more popular linux OS's like Ubuntu, PopOS, etc., but hopefully it's not an issue there as well otherwise that might be deterring folks from getting started with Krux because some who uses a linux OS mainly may not have a Mac handy.

Add support for upgrading firmware via microSD card

Two motivators here:

  1. Extra security for people wishing to verify the only data ever transmitted to the device comes from the card, and
  2. Potentially more convenient update process if both firmware and software can live on one card

Since the default firmware included with M5StickV has support for loading an arbitrary boot.py file it finds, it may be possible to exploit this in order to perform the initial firmware change via this mechanism as well.

MaixPy should be a submodule

Copying code in makes code review hard as now the reviewer also has check where that copied code came from and if it was modified. #39 sounds like this issue might be resolved by removal of the code but anyway, for a Bitcoin wallet code auditability is key.

Improve German translation

I used a translation app to make the German translation, so I'm sure it's terrible. If you know German, please improve it!

Add optional game of breakout to boot screen

On boot, a game of breakout starts where you need to get a certain score to "beat" the game and land on the Krux start menu.

Mostly a fun gimmick, but could maybe be useful in certain situations.

QR code compatibilty

Are the QR codes supposed to be compatible with SeedSigner?
I did a couple of tests and I was not able to scan any SeedSigner generated QR code, this error message came up: Invalid mnemonic length

Migrate from MaixPy to MicroPython

Move away from Sipeed's custom MaixPy fork of MicroPython so that the project won't be so tightly tied to the M5StickV / M5Stack.

The longer-term goal here is to move Krux toward platform independence so that eventually it could run on any of MicroPython's supported architectures

EDIT: I think there are two ways to approach this: 1) add shims to ports to give them a "maixpy-like" set of modules that Krux can use, or 2) find a way to add shims to MaixPy so that Krux code can be rewritten to rely on standard micropython modules.

Change "Check Address" to "Scan Address"

Right now, Check Address scans a QR code of a bitcoin address and begins deriving addresses of the current wallet to look for a match. If it finds a match, it displays the QR code.

I want to tweak this behavior so that it instead:

  1. Verifies it has scanned in a bitcoin address
  2. Immediately generates a QR that is displayed back, along with the (text) address. If you have a printer attached, you could print it on the follow-up screen per usual.
  3. After clicking through, you are asked if you want to check if the address belongs to your wallet, and then the existing check logic is performed.

With this slight change, Krux could act as an intermediary if you wanted to send funds to an address you don't own and would prefer to scan a QR code rather than copy-paste or type out an address on the computer/phone running the wallet coordinator. Scan a QR with Krux, display it back to the coordinator, make a transaction, sign.

This would also let you print copies of arbitrary bitcoin addresses. What could this be used for? Who knows...

Q: What is being imported _back_ into Krux from the wallet "coordinator"?

[This is not so much an issue as a question - I couldn't find a reference to any Krux discussion forum where I could ask it. BTW, if you don't have one yet I suggest starting a channel on Telegram which is where the SeedSigner / ColdCard / Raspiblitz / Specter / Sparrow and other projects hang out.]

The single-sig instructions (for Specter) proceed as follows: Create mnemonic, export to wallet coordinator via QR, then export from wallet coordinator back to Krux via QR. Question is: What is being moved back to the Krux that it doesn't already know from the mnemonic?

Add development/debugging instructions to README

After flashing the firmware and loading an SD card into the device, make sure to run vagrant halt to free the USB device, then run screen /dev/usbttydevicename 115200 for a live serial connection to see the output of print statements and/or drop into a python repl with Ctrl-C.

Add a Github Pages with better usage instructions / walkthrough examples

  • For wallet software to best read QR codes, hold the device 4-6 inches away from camera, tilt up or down slightly to reduce glare, and slowly move away and toward the camera.
  • To best read QR codes via the device's camera, hold the device just far enough away that the QR code takes up the entirety of the screen. If the code looks blurry and missing detail, the camera lens of the device can be focused by rotating it (with your fingertip) clockwise and counter-clockwise to achieve a clearer result. You should only have to do this the first time you use it.
  • You can now read in a receive address to verify that it's owned by the multsig to double-check that your desktop wallet software isn't lying to you

CMake Error when building the firmware

Thanks for this great project.

I am trying to build the firmware on a freshly installed Ubuntu system.
But CMake throws an error in Step 15/15 after vagrant ssh -c 'cd /vagrant; ./krux build-firmware':

-- builtin py dir: /src/MaixPy/projects/maixpy_m5stickv/builtin_py
-- [register component: micropython ], path:/src/MaixPy/components/micropython
CMake Error at /src/MaixPy/tools/cmake/compile.cmake:82 (message):
  Can not find port/src/speech/maix_asr/libmaix_asr.a or
  /src/MaixPy/components/micropython/port/src/speech/maix_asr/libmaix_asr.a
Call Stack (most recent call first):
  /src/MaixPy/components/micropython/CMakeLists.txt:564 (register_component)

Any idea what I'm missing here?

Add "printer" implementations that output gcode

This would allow people with CNC machines to mill their QR codes out of wood or steel.

Consider adding two "printers" to choose from:

  • gcode.FilePrinter - Outputs gcode to a .ngc file on a microSD card

  • gcode.GRBLPrinter - Streams gcode to a grbl controller over serial port connection

Add option to generate mnemonic from camera feed

It looks like SeedSigner does this, and it seems like a promising way to generate a mnemonic that is random if done right.

Will need to brush up on my stats knowledge, but here's my initial rough plan:

I'm thinking you would calculate entropy from the images using Shannon's formula and display to the user a progress bar / percent until enough entropy is collected. Once you have good/enough entropy, the words (numbers, really) are generated and then a Chi-squared test is performed on the generated words as a sanity check.

May want to also use a similarity function to compare the images and reject "duplicates" so that the user is forced to move the camera around?

Single-key wallet support

Arguments for and against? Leaving this open for comments / reactions to get a feel for how many people would want this added or not.

Add localizations

Krux has support for different languages. If it's missing a language or has an awkward translation, please file an issue or make a PR! Below is the current list of translations along with ones we would like to see added:

  • Vietnamese - #64
  • Spanish - #53
  • French - #41
  • German - #36
  • Esperanto
  • Romanian
  • Igbo
  • Czech
  • Tagalog
  • Swedish
  • Portuguese - #119
  • Polish
  • Italian

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.