[![Build Status](https://travis-ci.com/grinventions/mimblewimble-py.svg?branch=main)](https://travis-ci.com/grinventions/mimblewimble-py)

# Mimblewimble in Python

![mimblewimble-py logo](https://github.com/grinventions/mimblewimble-py/blob/main/assets/logo.png?raw=true)

We are building the first Python-based implementation of the Mimblewimble protocol for the [grin cryptocurrency](https://grin.mw/). At the moment it is at the most early stage of development. Heavily based on the [grin++ wallet](https://github.com/GrinPlusPlus/GrinPlusPlus).

## Usage

### Generating wallets

Simplest operation is simply make a new wallet

```python
from mimblewimble.wallet import Wallet

# instantiate the wallet
w = Wallet.initialize()

# derive the slatepack address and the recovery phrase
path = 'm/0/1/0'
slatepack_address = w.getSlatepackAddress(path=path)
recovery_phrase = w.getSeedPhrase()

# display  the output
print('Your slatepack address at the path {0} is'.format(path))
print(slatepack_address)
print()
print('Your recovery phrase is')
print(recovery_phrase)
```

it will respond

```
Your slatepack address at the path m/0/1/0 is
grin14xfltfnzfq68mc6k7xru469h2x0ejckzr7alczcjf2wml755qnuq8c0zkx

Your recovery phrase is
mammal scale present develop then tail identify movie pizza brisk entry regret match solve coffee empower double muffin curious virtual joy hen diagram vacuum
```

### Restoring wallet from the recovery phrase

You may restore the wallet from the recovery phrase as follows

```python
from mimblewimble.wallet import Wallet

# content of the core wallet encrypted seed file
recovery_phrase = 'sign interest obtain raw window monster jump bring nice crunch toward grunt prosper recycle sphere battle mother fold reject velvet emotion similar romance govern'

# instantiate the wallet
w = Wallet.fromSeedPhrase(recovery_phrase)

# derive the slatepack address and the recovery phrase
path = 'm/0/1/0'
slatepack_address = w.getSlatepackAddress(path=path)

# display  the output
print('Your slatepack address at the path {0} is'.format(path))
print(slatepack_address)
```

it will respond

```
Your slatepack address at the path m/0/1/0 is
grin14kgku7l5x6te3arast3p59zk4rteznq2ug6kmmypf2d6z8md76eqg3su35
```

### Restoring wallet from the encrypted seed

Fully compatible with seed generated by the core wallet

```python
from mimblewimble.wallet import Wallet

# content of the core wallet encrypted seed file
seed = {
    'encrypted_seed': '839773da8062af7dc51714fd98a7f9a72750e17aa54541d5317b5ea1be5c5751db85497aa630380dd984e2ecd603ae0b',
    'salt': '356f045acf2b2787',
    'nonce': 'b5a490e1c942e6a5147bb740'
}

# convert to bytes
encrypted_seed = bytes.fromhex(seed['encrypted_seed'])
nonce = bytes.fromhex(seed['nonce'])
salt = bytes.fromhex(seed['salt'])

# don't forget your password
password = 'grinventions'

# instantiate the wallet
w = Wallet(encrypted_seed=encrypted_seed, nonce=nonce, salt=salt)

# decrypt
w.unshieldWallet(password, nonce=nonce, salt=salt)

# derive the slatepack address and the recovery phrase
path = 'm/0/1/0'
slatepack_address = w.getSlatepackAddress(path=path)
recovery_phrase = w.getSeedPhrase()

# display  the output
print('Your slatepack address at the path {0} is'.format(path))
print(slatepack_address)
print()
print('Your recovery phrase is')
print(recovery_phrase)
```

it will respond

```
grin14kgku7l5x6te3arast3p59zk4rteznq2ug6kmmypf2d6z8md76eqg3su35

Your recovery phrase is
sign interest obtain raw window monster jump bring nice crunch toward grunt prosper recycle sphere battle mother fold reject velvet emotion similar romance govern
```

### Detecting invalid password

While the master seed is being encrypted, the MAC tag digest will be verified indicating if password was correct.

```python
from mimblewimble.wallet import Wallet

# content of the core wallet encrypted seed file
seed = {
    'encrypted_seed': '839773da8062af7dc51714fd98a7f9a72750e17aa54541d5317b5ea1be5c5751db85497aa630380dd984e2ecd603ae0b',
    'salt': '356f045acf2b2787',
    'nonce': 'b5a490e1c942e6a5147bb740'
}

# convert to bytes
encrypted_seed = bytes.fromhex(seed['encrypted_seed'])
nonce = bytes.fromhex(seed['nonce'])
salt = bytes.fromhex(seed['salt'])

# don't forget your invalid password
password = 'Lt. Col. Frank Slade'

# instantiate the wallet
w = Wallet(encrypted_seed=encrypted_seed, nonce=nonce, salt=salt)

# decrypt
valid = True
try:
    w.unshieldWallet(password, nonce=nonce, salt=salt)
except Exception as e:
    if str(e) == 'MAC check failed':
        valid = False
if valid:
    print('Password correct!')
else:
    print('Password invalid!')
```

it will indicate failure of verification of the MAC tag

```
Password invalid!
```

### Building coinbase

```python
from mimblewimble.wallet import Wallet

# instantiate the wallet
w = Wallet.initialize()

# pick path and amount
coinbase_path = 'm/0/1/0'
coinbase_amount = 60

kernel, output = w.createCoinbase(coinbase_amount, path=coinbase_path)

# display  the output
print('Kernel')
print(kernel.toJSON())
print('Output')
print(output.output.toJSON())
```

it will output something like

```
Kernel
{'features': {}, 'excess': '0927759d4f4fc554e148f1906166381b6c1889895c6f96c3e2e76c55c9e219848b', 'excess_sig': ''}
Output
{'features': 1, 'commit': '098dcf471cf019030c82044cee5e794b0e31d11e00567920d8e5a40103eb63071f', 'proof': ' '}
```

### SRS transaction building

```python
from mimblewimble.wallet import Wallet

# instantiate two wallets wallet
alice_path = 'm/0/1/0'
alice_wallet = Wallet.initialize()
alice_address = alice_wallet.getSlatepackAddress()

bob_path = 'm/0/1/0'
bob_wallet = Wallet.initialize()
bob_address = bob_wallet.getSlatepackAddress()

print('Alice: ', alice_address)
print('Bob:   ', bob_address)

# Alice makes 60 coins coinbase output
coinbase_amount = 60000000000
kernel, output = alice_wallet.createCoinbase(
    coinbase_amount, path=alice_path)

# attempts to send 30 coins to Bob
num_change_outputs = 1
amount = 30000000000
fee_base = 7000000
block_height = 99999
send_slate, alice_secret_key, alice_secret_nonce, change_outputs = alice_wallet.send(
    [output], num_change_outputs, amount, fee_base, block_height,
    path=alice_path, receiver_address=bob_address)

print()
print('send slate from Alice')
print(send_slate.toJSON())

# build the receive slate using Bob's wallet
receive_slate, bob_secret_key, bob_secret_nonce = bob_wallet.receive(send_slate)

print()
print('receive slate from Bob')
print(receive_slate.toJSON())

# finalize the receive slate using Alice's wallet
finalized_slate = alice_wallet.finalize(
    receive_slate, path=alice_path)

print()
print('finalized slate that Alice has')
print(finalized_slate.toJSON())
```

expect output of the form

```
Alice:  grin1rn9jvtzlffsk4dht29nqtw8ja65r749jvmcm3833kadt76dajr4qra9e6m
Bob:    grin18gxjdmmq53fpx9330atjqs8x3tc7jw6dcthe043pzrr9d2nletqsnt3pu9

send slate from Alice
{'amt': 30000000000, 'sta': 'S1', 'off': 'a18fa6bfd76257149e449bd8bd816a4ce3de8af539a794f937c1d39dc78b771e', 'fee': 322000000, 'coms': [{'c': '09ea9b319f2bbf94eb21f8e996e42fb2c2968e939bf18e8acdbd4192546df16296', 'f': 1}, {'c': '09e17a9b2eed70ef1438a449f9c89eb7a795a71c3e0f398bf5f13b6c8a814aaac0', 'p': ' '}], 'proof': {'saddr': '1ccb262c5f4a616ab6eb516605b8f2eea83f54b266f1b89e31b75abf69bd90ea', 'raddr': None, 'rsig': None}}

receive slate from Bob
{'amt': 30000000000, 'sta': 'S2', 'off': '84b02f977be855ca2a748362aa535da833a4bb7786ac7263e880f1d9b00ac3fb', 'fee': 322000000, 'coms': [{'c': '09ea9b319f2bbf94eb21f8e996e42fb2c2968e939bf18e8acdbd4192546df16296', 'f': 1}, {'c': '09e17a9b2eed70ef1438a449f9c89eb7a795a71c3e0f398bf5f13b6c8a814aaac0', 'p': ' '}, {'c': '092540d07c1dde2de274ac14f0e42d6e542851c3e7bbb0987b19354b9999800aa1', 'p': ' '}], 'proof': {'saddr': '1ccb262c5f4a616ab6eb516605b8f2eea83f54b266f1b89e31b75abf69bd90ea', 'raddr': '3a0d26ef60a4521316317f572040e68af1e93b4dc2ef97d62110c656aa7fcac1', 'rsig': '35392393ba925f976c9fee85424489a9d6116f1a1a4547d133056a39215714902d172a1ea8b3271929fdf6ae981ae7ec264095fd98300f9ced73be50644f500d00000006fc23ac0008aae8f9a55ebbc33f5b13ba1c9eadd4218a514360c4d9c10be9c9b681e8d86ccb1ccb262c5f4a616ab6eb516605b8f2eea83f54b266f1b89e31b75abf69bd90ea'}}

finalized slate that Alice has
{'amt': 30000000000, 'sta': 'S3', 'off': '84b02f977be855ca2a748362aa535da833a4bb7786ac7263e880f1d9b00ac3fb', 'fee': 322000000, 'coms': [{'c': '09ea9b319f2bbf94eb21f8e996e42fb2c2968e939bf18e8acdbd4192546df16296', 'f': 1}, {'c': '09e17a9b2eed70ef1438a449f9c89eb7a795a71c3e0f398bf5f13b6c8a814aaac0', 'p': ' '}, {'c': '092540d07c1dde2de274ac14f0e42d6e542851c3e7bbb0987b19354b9999800aa1', 'p': ' '}], 'proof': {'saddr': '1ccb262c5f4a616ab6eb516605b8f2eea83f54b266f1b89e31b75abf69bd90ea', 'raddr': '3a0d26ef60a4521316317f572040e68af1e93b4dc2ef97d62110c656aa7fcac1', 'rsig': '35392393ba925f976c9fee85424489a9d6116f1a1a4547d133056a39215714902d172a1ea8b3271929fdf6ae981ae7ec264095fd98300f9ced73be50644f500d00000006fc23ac0008aae8f9a55ebbc33f5b13ba1c9eadd4218a514360c4d9c10be9c9b681e8d86ccb1ccb262c5f4a616ab6eb516605b8f2eea83f54b266f1b89e31b75abf69bd90ea'}}
```

### Deriving TOR addresses

You may use `mimblewimble-py` to convert grin address to .onion address, which is useful in checking if wallet is reachable.

```python
from mimblewimble.helpers.tor import TorAddress
from mimblewimble.keychain import KeyChain

slatepack_address = 'grin1m3ckuft0llw97ulzmedk557twyn76wkgxartn6lpfq5xd9wcc24qnpwde5'

# ed25519 public key from slatepack address
ed25519_pk = KeyChain.slatepackAddressToED25519PublicKey(slatepack_address)

# ed25519 public key to .onion address
onion_address = TorAddress(ed25519_pk).toOnion()

assert onion_address == '3ryw4jlp77of647c3znwuu6loet62owig5dlt27bjaugnfoyykvneayd.onion'

# you can also validate the .onion address
# it will check if ed25519 public key is a valid curve point
# and also if checksum is correct, only V3 TOR addresses are supported!
TorAddress.parse(onion_address)

print(slatepack_address)
print(onion_address)
```

outputs

```
grin1m3ckuft0llw97ulzmedk557twyn76wkgxartn6lpfq5xd9wcc24qnpwde5
3ryw4jlp77of647c3znwuu6loet62owig5dlt27bjaugnfoyykvneayd.onion
```

you may use TOR proxy to reach foreign API listener under `3ryw4jlp77of647c3znwuu6loet62owig5dlt27bjaugnfoyykvneayd.onion` to check if wallet is listening.

## Expected features

* Managing blocks
* Managing transactions

## Use-cases

* Implement python-based wallets and nodes for [grin](https://grin.mw/)
* [Research](https://forum.grin.mw/c/research/11) new protocols, quickly drafting ideas and testing them
* Have [grin](https://grin.mw/) codebase that anyone can easily understand and translate to other languages

## Useful docs

1. Regarding serialization/deserialization [p2p protocol document](https://github.com/mimblewimble/docs/wiki/P2P-Protocol#compactblockbody)

## Tools

1. [Python's BIP32](https://pypi.org/project/bip32/)

## Support

This project is NOT financed from the grin fund neither grin community fund. I deliverately did not request funding because of the following reasons:

1. I am not certain how much time I will be able to dedicate to it
2. I want this project to earn trust from the community, not have it guaranteed upfront

Anyone who wishes to support this project is welcome to donate to the following grin address

```
grin1vcjsgk6rltncqh7cxjywukjfrf825d8a6xk77msfuhf9ev3r55wq7l2ng4
```

which is my donation address, my username is [@marekyggdrasil](https://github.com/marekyggdrasil) and if you want to know more about on the [grin forum](https://forum.grin.mw/) I am known as [@renzokuken](https://forum.grin.mw/u/renzokuken/summary) me check [my website](https://mareknarozniak.com/).
