Giter Site home page Giter Site logo

spacemeshos / app-spacemesh Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ledgerhq/app-solana

0.0 2.0 0.0 900 KB

Spacemesh app for Ledger Wallet

License: Apache License 2.0

Shell 0.99% C++ 3.69% Python 5.03% C 77.21% Rust 11.82% Makefile 0.98% CMake 0.28%

app-spacemesh's Introduction

Spacemesh app for Ledger Wallet

Overview

This app adds support for the Spacemesh native token to Ledger hardware wallets.

Current Features:

  • Pubkey queries
  • Parse, display and sign all Spacemesh CLI generated transaction formats
  • Blind sign arbitrary transactions (Enabled via settings)

Prerequisites

For building the app

Get the Ledger App Builder Docker image

Pull the latest "full" image:

> docker pull ghcr.io/ledgerhq/ledger-app-builder/ledger-app-builder:latest

For working with the device

If you're able to successfully build and load the app using the docker images as described below, you probably don't need to install ledgerblue as it's pre-installed in the docker images. If, however, you have issues with the docker build and load process you can try using ledgerblue directly.

Follow the instructions in the blue-loader-python repository to install the ledgerblue python module. We strongly recommend using a virtualenv as suggested.

For running the test suite

Build

We recommend building using Ledger's provided ledger-app-builder Docker image. The full steps follow. A convenience wrapper script (./docker-make) has been provided for simplicity but it may not work out of the box on all configurations. Instructions on using this script are below.

Using the Ledger App Builder Docker image

Note: These instructions have been tested on Linux and macOS. They may differ slightly for other platforms. Feel free to open an issue in this repository if you encounter issues on other platforms.

  1. Pull the latest "full" image (as described above)

  2. Run the image

> docker run --rm -ti  -v "$(realpath .):/app" --privileged ghcr.io/ledgerhq/ledger-app-builder/ledger-app-builder:latest
  • The --privileged flag is required to allow the Docker container to access your Ledger device via USB
  • If permissions errors are encountered, ensure that your user is in the docker group and that the session has been restarted
  1. Set BOLOS_SDK to the correct SDK name for your device, then run make inside the Docker container. E.g., for Nano S:
bash-5.1# BOLOS_SDK=$NANOS_SDK make

Load

It's possible to load the app directly onto a physical Ledger device using a process called sideloading, using the ledgerblue Python module. Note that sideloading is only supported on Nano S and Blue devices, and not on Nano X. See the ledgerblue documentation for more information.

The simplest way to load the app is to build it using the Docker image as described above, then run the load command inside the container:

bash-5.1# BOLOS_SDK=$NANOS_SDK make load

Tap right on the device to view the (randomly generated) Public Key, then press both buttons to "Allow unsafe manager." If the app is already installed, you'll be prompted to delete it. Then when you see "Install app Spacemesh", tap right a few times through the Identifier and Code Id screens until you see "Perform Installation." Press both buttons and enter the device PIN to perform the installation.

  • If you get a segmentation fault during the load process (fairly common on Linux), try physically disconnecting and reconnecting the Ledger device, then close and reopen the Docker instance.
  • If you get the error ledgerblue.commException.CommException: Exception : No dongle found on macOS, try running the full load command natively (i.e., outside of the Docker container) using the latest version of ledgerblue. Install ledgerblue as outlined above, then copy and paste the load command, which should look something like this:
> python3 -m ledgerblue.loadApp --curve ed25519 --appFlags 0xa00  --path "44'/540'" --tlv --targetId 0x33100004 --targetVersion="" --apiLevel 1 --delete --fileName bin/app.hex --appName "Spacemesh" --appVersion "0.1.0" --dataSize $((0x`cat debug/app.map |grep _envram_data | tr -s ' ' | cut -f2 -d' '|cut -f2 -d'x'` - 0x`cat debug/app.map |grep _nvram_data | tr -s ' ' | cut -f2 -d' '|cut -f2 -d'x'`)) `ICONHEX=\`python3 $BOLOS_SDK/icon3.py --hexbitmaponly icons/nanox_app_spacemesh.gif  2>/dev/null\` ; [ ! -z "$ICONHEX" ] && echo "--icon $ICONHEX"`
  • Make sure $BOLOS_SDK is set to the location of the checked-out copy of the Ledger SDK. Note that, if this location is wrong or the icon3.py script is not found, the app will appear on the device with an empty icon.
  • Note that the --targetId flag and the icon filename will differ depending which Ledger device you're using.

Using docker-make

docker-make manages the current target SDK for you, automatically setting BOLOS_SDK to the correct path when the Docker container is launched. A TARGET_SDK must be specified when building from clean and clean must be run before switching

TARGET_SDK

Moniker Device
s Nano S
x Nano X
sp Nano S+
./docker-make <TARGET_SDK>

Clean

./docker-make clean

Working with the device

Requires that the BOLOS_SDK envvar be set. This can be achieved by first building for the desired target device.

Load

make load-only

Delete

make delete

Test

Unit

Run C tests:

make -C libsol

Integration

First enable blind-signing in the App settings

cargo run --manifest-path tests/Cargo.toml

app-spacemesh's People

Contributors

askibin avatar bigspider avatar criesofcarrots avatar fbeutin-ledger avatar fkbenjamin avatar garious avatar grydz avatar jibeee avatar leoluk avatar lpascal-ledger avatar lrettig avatar meriadec avatar niooss-ledger avatar rgeslain-ledger avatar saltari avatar sleepdefic1t avatar t-nelson avatar tamtamhero avatar yhql avatar

Watchers

 avatar  avatar

app-spacemesh's Issues

Add transaction signing

@lrettig
hello,now can i use the ledger app code to sign my transaction?
when i signing , the source code need the message header ,but the spacemesh example code not contains that.

the ledger app code path: app-spacemesh->src->signMessage.c

if (parse_message_header(&parser, header) != 0) {
        // This is not a valid Solana message
        THROW(ApduReplySolanaInvalidMessage);
    }
int parse_message_header(Parser* parser, MessageHeader* header) {
    BAIL_IF(parse_version(parser, header));
    BAIL_IF(parse_pubkeys(parser, &header->pubkeys_header, &header->pubkeys));
    BAIL_IF(parse_blockhash(parser, &header->blockhash));
    BAIL_IF(parse_length(parser, &header->instructions_length));
    return 0;
}

the spacemesh code path: go-spacemesh->genvm->sdk->wallet->tx.go

// Spend creates spend transaction.
func Spend(pk signing.PrivateKey, to types.Address, amount uint64, nonce types.Nonce, opts ...sdk.Opt) []byte {
	options := sdk.Defaults()
	for _, opt := range opts {
		opt(options)
	}

	spawnargs := wallet.SpawnArguments{}
	copy(spawnargs.PublicKey[:], signing.Public(pk))
	principal := core.ComputePrincipal(wallet.TemplateAddress, &spawnargs)

	payload := core.Payload{}
	payload.GasPrice = options.GasPrice
	payload.Nonce = nonce

	args := wallet.SpendArguments{}
	args.Destination = to
	args.Amount = amount

	tx := encode(&sdk.TxVersion, &principal, &sdk.MethodSpend, &payload, &args)
	sig := ed25519.Sign(ed25519.PrivateKey(pk), core.SigningBody(options.GenesisID[:], tx))
	return append(tx, sig...)
}

above all , It doesn't seem to match. the ledger app code only can used on the tx of solana rule ,but failed to submit for spacemesh node.

ps : i try sign tx by solana rule, the ledger app code working success.

trans, err := solana.NewTransaction(
		[]solana.Instruction{
			system.NewTransferInstruction(
				uint64(toAmount),
				solana.PublicKey(fromAddrInfo.PublicKey),
				solana.PublicKey(toAddrInfo.PublicKey),
			).Build(),
		},
		solana.Hash(stateHashResp.Response.RootHash),
		solana.TransactionPayer(solana.PublicKey(fromAddrInfo.PublicKey)),
	)
	binary, err := trans.Message.MarshalBinary()
	if err != nil {
		return "", fmt.Errorf("marshal trans binary err:%v", err)
	}
//  the binary bytes to  sign  success

Installing app on Nano S with newest Firmware

On macOS to install the app on Nano S with Firmware 2.1.0 the command in the README.md needs to be changed to:

python3 -m ledgerblue.loadApp --curve ed25519 --appFlags 0x800 --path "44'/540'" --tlv --targetId 0x31100004 --targetVersion="2.1.0" --delete --fileName bin/app.hex --appName "Spacemesh" --appVersion "0.1.0" --dataSize $((0x`cat debug/app.map |grep _envram_data | tr -s ' ' | cut -f2 -d' '|cut -f2 -d'x'` - 0x`cat debug/app.map |grep _nvram_data | tr -s ' ' | cut -f2 -d' '|cut -f2 -d'x'`)) `ICONHEX=\`python3 $BOLOS_SDK/icon3.py --hexbitmaponly icons/nanos_app_spacemesh.gif  2>/dev/null\` ; [ ! -z "$ICONHEX" ] && echo "--icon $ICONHEX"`

The --targetId needs to be 0x31100004 (according to official documentation for Firmware 1.5.x of Nano S), the --appFlags are 0x800 instead of 0xa00, --apiLevel isn't needed and the path to the .gif needs to be nanos_* instead of nanox_*.

Get tests working again

There are currently four types of tests in the GHA CI workflow (forked from upstream):

  • Code style check - passing
  • Sonarcloud - Added credentials, passing
  • Swap functional tests - I suspect we want to disable this for now or remove it entirely.
  • Compilation & tests - ragger tests are failing due to changed HD path. Fixing this will require updating the hardcoded image files in tests/python/snapshots. Note that the workflow file uploads the images as artifacts. Either download these and replace the existing images, or run locally and do the same. I tried this but it won't work on ARM on macOS or Linux. On amd64 ubuntu I get past this step but get errors like the below, which are probably a speculos issue. Haven't been able to troubleshoot this further.

Then there's also Rust tests (tests/src/main.rs). These do NOT run in CI since they required a physically connected device. The tests rely on the solana SDK and won't work since we've updated the derivation path. They should be rewritten to use https://github.com/spacemeshos/spacemesh-sdk/ (should be an easy change), and we can consider removing or temporarily disabling tests for the tx types we don't support.

======================================================================== ERRORS =========================================================================
____________________________________ ERROR at setup of TestGetPublicKey.test_solana_get_public_key_ok[nanosp 1.0.4] _____________________________________
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connectionpool.py:790: in urlopen
    response = self._make_request(
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connectionpool.py:536: in _make_request
    response = conn.getresponse()
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connection.py:454: in getresponse
    httplib_response = super().getresponse()
/usr/lib/python3.10/http/client.py:1374: in getresponse
    response.begin()
/usr/lib/python3.10/http/client.py:318: in begin
    version, status, reason = self._read_status()
/usr/lib/python3.10/http/client.py:279: in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
/usr/lib/python3.10/socket.py:705: in readinto
    return self._sock.recv_into(b)
E   ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:
../../.pyenv/versions/ragger/lib/python3.10/site-packages/requests/adapters.py:486: in send
    resp = conn.urlopen(
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connectionpool.py:844: in urlopen
    retries = retries.increment(
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/util/retry.py:470: in increment
    raise reraise(type(error), error, _stacktrace)
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/util/util.py:38: in reraise
    raise value.with_traceback(tb)
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connectionpool.py:790: in urlopen
    response = self._make_request(
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connectionpool.py:536: in _make_request
    response = conn.getresponse()
../../.pyenv/versions/ragger/lib/python3.10/site-packages/urllib3/connection.py:454: in getresponse
    httplib_response = super().getresponse()
/usr/lib/python3.10/http/client.py:1374: in getresponse
    response.begin()
/usr/lib/python3.10/http/client.py:318: in begin
    version, status, reason = self._read_status()
/usr/lib/python3.10/http/client.py:279: in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
/usr/lib/python3.10/socket.py:705: in readinto
    return self._sock.recv_into(b)
E   urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

Built app is very large

The Spacemesh App is ~105 KB in size when built with the steps outlined in the README.md this is quite large in comparison with other apps:

  • Bitcoin (58 K)
  • Etherum (50 K)
  • solana (36 K)

The Nano S only has 135 K of space available which makes it impossible to install any other apps besides Spacemesh. Since the Spacemesh app is similar in its features to solana it is weird that the app is 3x its size.

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.