Status deprecated update2 (#134)

These are from the previous PR:
https://github.com/vacp2p/rfc-index/pull/109

---------

Co-authored-by: Jimmy Debe <91767824+jimstir@users.noreply.github.com>
This commit is contained in:
Cofson
2025-04-29 10:24:09 +02:00
committed by GitHub
parent 5971166405
commit 614348a498
19 changed files with 5125 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
---
title: 3RD-PARTY
name: 3rd party
status: deprecated
description: This specification discusses 3rd party APIs that Status relies on.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Volodymyr Kozieiev <volodymyr@status.im>
---
## Abstract
This specification discusses 3rd party APIs that Status relies on.
These APIs provide various capabilities, including:
- communicating with the Ethereum network,
- allowing users to view address and transaction details on external websites,
- retrieving fiat/crypto exchange rates,
- obtaining information about collectibles,
- hosting the privacy policy.
## Definitions
| Term | Description |
|-------------------|-------------------------------------------------------------------------------------------------------|
| Fiat money | Currency established as money, often by government regulation, but without intrinsic value. |
| Full node | A computer, connected to the Ethereum network, that enforces all Ethereum consensus rules. |
| Crypto-collectible| A unique, non-fungible digital asset, distinct from cryptocurrencies where tokens are identical. |
## Why 3rd Party APIs Can Be a Problem
Relying on 3rd party APIs conflicts with Statuss censorship-resistance principle.
Since Status aims to avoid suppression of information,
it is important to minimize reliance on 3rd parties that are critical to app functionality.
## 3rd Party APIs Used by the Current Status App
### Infura
**What is it?**
Infura hosts a collection of Ethereum full nodes and provides an API
to access the Ethereum and IPFS networks without requiring a full node.
**How Status Uses It**
Since Status operates on mobile devices,
it cannot rely on a local node.
Therefore, all Ethereum network communication happens via Infura.
**Concerns**
Making an HTTP request can reveal user metadata,
which could be exploited in attacks if Infura is compromised.
Infura uses centralized hosting providers;
if these providers fail or cut off service,
Ethereum-dependent features in Status would be affected.
### Etherscan
**What is it?**
Etherscan is a service that allows users to explore the Ethereum blockchain
for transactions, addresses, tokens, prices,
and other blockchain activities.
**How Status Uses It**
The Status Wallet allows users to view address and transaction details on Etherscan.
**Concerns**
If Etherscan becomes unavailable,
users wont be able to view address or transaction details through Etherscan.
However, in-app information will still be accessible.
### CryptoCompare
**What is it?**
CryptoCompare provides live crypto prices, charts, and analysis from major exchanges.
**How Status Uses It**
Status regularly fetches crypto prices from CryptoCompare,
using this information to calculate fiat values
for transactions or wallet assets.
**Concerns**
HTTP requests can reveal metadata,
which could be exploited if CryptoCompare is compromised.
If CryptoCompare becomes unavailable,
Status wont be able to show fiat equivalents for crypto in the wallet.
### Collectibles
Various services provide information on collectibles:
- [Service 1](https://api.pixura.io/graphql)
- [Service 2](https://www.etheremon.com/api)
- [Service 3](https://us-central1-cryptostrikers-prod.cloudfunctions.net/cards/)
- [Service 4](https://api.cryptokitties.co/)
**Concerns**
HTTP requests can reveal metadata,
which could be exploited if these services are compromised.
### Iubenda
**What is it?**
Iubenda helps create compliance documents for websites and apps across jurisdictions.
**How Status Uses It**
Statuss privacy policy is hosted on Iubenda.
**Concerns**
If Iubenda becomes unavailable,
users will be unable to view the app's privacy policy.
## Changelog
| Version | Comment |
|---------|-----------------|
| 0.1.0 | Initial release |
## Copyright
Copyright and related rights waived via CC0.
## References
- [GraphQL](https://api.pixura.io/graphql)
- [Etheremon](https://www.etheremon.com/api)
- [Cryptostrikers](https://us-central1-cryptostrikers-prod.cloudfunctions.net/cards/)
- [Cryptokitties](https://api.cryptokitties.co/)

View File

@@ -0,0 +1,138 @@
---
title: IPFS-gateway-for-Sticker-Pack
name: IPFS gateway for Sticker Pack
status: deprecated
description: This specification describes how Status uses the IPFS gateway to store stickers.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Gheorghe Pinzaru <gheorghe@status.im>
---
## Abstract
This specification describes how Status uses the IPFS gateway
to store stickers.
The specification explores image format,
how a user uploads stickers,
and how an end user can see them inside the Status app.
## Definition
| Term | Description |
|------------------|----------------------------------------------------------------------------------------|
| **Stickers** | A set of images which can be used to express emotions |
| **Sticker Pack** | ERC721 token which includes the set of stickers |
| **IPFS** | P2P network used to store and share data, in this case, the images for the stickerpack |
## Specification
### Image format
Accepted image file types are `PNG`, `JPG/JPEG` and `GIF`,
with a maximum allowed size of 300kb.
The minimum sticker image resolution is 512x512,
and its background SHOULD be transparent.
### Distribution
The node implements sticker packs as [ERC721 token](https://eips.ethereum.org/EIPS/eip-721)
and contain a set of stickers.
The node stores these stickers inside the sticker pack as a set of hyperlinks pointing to IPFS storage.
These hyperlinks are publicly available and can be accessed by any user inside the status chat.
Stickers can be sent in chat only by accounts that own the sticker pack.
### IPFS gateway
At the moment of writing, the current main Status app uses the [Infura](https://infura.io/) gateway.
However, clients could choose a different gateway or to run own IPFS node.
Infura gateway is an HTTPS gateway,
which based on an HTTP GET request with the multihash block will return the stored content at that block address.
The node requires the use of a gateway to enable easy access to the resources over HTTP.
The node stores each image of a sticker inside IPFS using a unique address that is
derived from the hash of the file.
This ensures that a file can't be overridden,
and an end-user of the IPFS will receive the same file at a given address.
### Security
The IPFS gateway acts as an end-user of the IPFS
and allows users of the gateway to access IPFS without connection to the P2P network.
Usage of a gateway introduces potential risk for the users of that gateway provider.
In case of a compromise in the security of the provider, meta information such as IP address,
User-Agent and other of its users can be leaked.
If the provider servers are unavailable the node loses access through the gateway to the IPFS network.
### Status sticker usage
When the app shows a sticker, the Status app makes an HTTP GET request to IPFS gateway using the hyperlink.
To send a sticker in chat, a user of Status should buy or install a sticker pack.
To be available for installation a Sticker Pack should be submitted to Sticker market by an author.
#### Submit a sticker
To submit a sticker pack, the author should upload all assets to IPFS.
Then generate a payload including name, author, thumbnail,
preview and a list of stickers in the [EDN format](https://github.com/edn-format/edn). Following this structure:
``
{meta {:name "Sticker pack name"
:author "Author Name"
:thumbnail "e30101701220602163b4f56c747333f43775fdcbe4e62d6a3e147b22aaf6097ce0143a6b2373"
:preview "e30101701220ef54a5354b78ef82e542bd468f58804de71c8ec268da7968a1422909357f2456"
:stickers [{:hash "e301017012207737b75367b8068e5bdd027d7b71a25138c83e155d1f0c9bc5c48ff158724495"}
{:hash "e301017012201a9cdea03f27cda1aede7315f79579e160c7b2b6a2eb51a66e47a96f47fe5284"}]}}
``
All asset fields, are contenthash fields as per [EIP 1577](https://eips.ethereum.org/EIPS/eip-1577).
The node also uploads this payload to IPFS, and the node uses the IPFS address in the content field of the Sticker Market contract.
See [Sticker Market spec](https://github.com/status-im/sticker-market/blob/651e88e5f38c690e57ecaad47f46b9641b8b1e27/docs/specification.md) for a detailed description of the contract.
#### Install a sticker pack
To install a sticker pack, the node fetches all sticker packs available in Sticker Market.
The node needs the following steps to fetch all sticker packs:
#### 1. Get total number of sticker packs
Call `packCount()` on the sticker market contract, will return number of sticker pack registered as `uint256`.
#### 2. Get sticker pack by id
ID's are represented as `uint256` and are incremental from `0` to total number of sticker packs in the contract,
received in the previous step.
To get a sticker pack call `getPackData(sticker-pack-id)`, the return type is `["bytes4[]" "address" "bool" "uint256" "uint256" "bytes"]`
which represents the following fields: `[category owner mintable timestamp price contenthash]`.
Price is the SNT value in wei set by sticker pack owner.
The contenthash is the IPFS address described in the [submit description](#submit-a-sticker) above.
Other fields specification could be found in [Sticker Market spec](https://github.com/status-im/sticker-market/blob/651e88e5f38c690e57ecaad47f46b9641b8b1e27/docs/specification.md)
##### 3. Get owned sticker packs
The current Status app fetches owned sticker packs during the open of any sticker view
(a screen which shows a sticker pack, or the list of sticker packs).
To get owned packs, get all owned tokens for the current account address,
by calling `balanceOf(address)` where address is the address for the current account.
This method returns a `uint256` representing the count of available tokens. Using `tokenOfOwnerByIndex(address,uint256)` method,
with the address of the user and ID in form of a `uint256`
which is an incremented int from 0 to the total number of tokens, gives the token id.
To get the sticker pack id from a token call`tokenPackId(uint256)` where `uint256` is the token id.
This method will return an `uint256` which is the id of the owned sticker pack.
##### 4. Buy a sticker pack
To buy a sticker pack call `approveAndCall(address,uint256,bytes)`
where `address` is the address of buyer,`uint256` is the price and third parameters `bytes` is the callback called if approved.
In the callback, call `buyToken(uint256,address,uint256)`, first parameter is sticker pack id, second buyers address, and the last is the price.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [ERC721 Token Standard](https://eips.ethereum.org/EIPS/eip-721)
- [Infura](https://infura.io/)
- [EDN Format](https://github.com/edn-format/edn)
- [EIP 1577](https://eips.ethereum.org/EIPS/eip-1577)
- [Sticker Market Specification](https://github.com/status-im/sticker-market/blob/651e88e5f38c690e57ecaad47f46b9641b8b1e27/docs/specification.md)

View File

@@ -0,0 +1,457 @@
---
title: ACCOUNT
name: Account
status: deprecated
description: This specification explains what a Status account is, and how a node establishes trust.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Corey Petty <corey@status.im>
- Oskar Thorén <oskar@status.im>
- Samuel Hawksby-Robinson <samuel@status.im>
---
## Abstract
This specification explains what a Status account is,
and how a node establishes trust.
## Introduction
The core concept of an account in Status is a set of cryptographic keypairs.
Namely, the combination of the following:
1. a Whisper/Waku chat identity keypair
1. a set of cryptocurrency wallet keypairs
The node verifies or derives everything else associated with the contact from the above items, including:
- Ethereum address (future verification, currently the same base keypair)
- 3 word mnemonic name
- identicon
- message signatures
## Initial Key Generation
### Public/Private Keypairs
- An ECDSA (secp256k1 curve) public/private keypair MUST be generated via a [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki) derived path from a [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase.
- The default paths are defined as such:
- Whisper/Waku Chat Key (`IK`): `m/43'/60'/1581'/0'/0` (post Multiaccount integration)
- following [EIP1581](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1581.md)
<!-- WE CURRENTLY DO NOT IMPLEMENT ENCRYPTION KEY, FOR FUTURE - C.P. -->
<!-- - DB encryption Key (`DBK`): `m/43'/60'/1581'/1'/0` (post Multiaccount integration) -->
<!-- - following [EIP1581](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1581.md) -->
- Status Wallet paths: `m/44'/60'/0'/0/i` starting at `i=0`
- following [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
- NOTE: this (`i=0`) is also the current (and only) path for Whisper/Waku key before Multiaccount integration
### X3DH Prekey bundle creation
- Status follows the X3DH prekey bundle scheme that [Open Whisper Systems](https://en.wikipedia.org/wiki/Signal_Messenger#2013%E2%80%932018:_Open_Whisper_Systems) (not to be confused with the Whisper sub-protocol) outlines [in their documentation](https://signal.org/docs/specifications/x3dh/#the-x3dh-protocol) with the following exceptions:
- Status does not publish one-time keys `OPK` or perform DH including them, because there are no central servers in the Status implementation.
- A client MUST create X3DH prekey bundles, each defined by the following items:
- Identity Key: `IK`
- Signed prekey: `SPK`
- Prekey signature: `Sig(IK, Encode(SPK))`
- Timestamp
- These bundles are made available in a variety of ways, as defined in section 2.1.
## Account Broadcasting
- A user is responsible for broadcasting certain information publicly so that others may contact them.
### X3DH Prekey bundles
- A client SHOULD regenerate a new X3DH prekey bundle every 24 hours. This MAY be done in a lazy way, such that a client that does not come online past this time period does not regenerate or broadcast bundles.
- The current bundle SHOULD be broadcast on a Whisper/Waku topic specific to his Identity Key, `{IK}-contact-code`, intermittently. This MAY be done every 6 hours.
- A bundle SHOULD accompany every message sent.
- TODO: retrieval of long-time offline users bundle via `{IK}-contact-code`
## Optional Account additions
### ENS Username
- A user MAY register a public username on the Ethereum Name System (ENS). This username is a user-chosen subdomain of the `stateofus.eth` ENS registration that maps to their Whisper/Waku identity key (`IK`).
<!-- ### User Profile Picture
- An account MAY edit the `IK` generated identicon with a chosen picture. This picture will become part of the publicly broadcast profile of the account. -->
<!-- TODO: Elaborate on wallet account and multiaccount -->
<!-- TODO: Elaborate on security implications -->
## Trust establishment
**Trust establishment deals with users verifying they are communicating with who they think they are.**
### Terms Glossary
| term | description |
| ------------------------- | ----------- |
| privkey | ECDSA secp256k1 private key |
| pubkey | ECDSA secp256k1 public key |
| Whisper/Waku key | pubkey for chat with HD derivation path m/43'/60'/1581'/0'/0 |
### Contact Discovery
#### Public channels
- Public group channels in Status are a broadcast/subscription system. All public messages are encrypted with a symmetric key derived from the channel name, `K_{pub,sym}`, which is publicly known.
- A public group channel's symmetric key MUST creation must follow the [web3 API](https://web3js.readthedocs.io/en/1.0/web3-shh.html#generatesymkeyfrompassword)'s `web3.ssh.generateSymKeyFromPassword` function
- In order to post to a public group channel, a client MUST have a valid account created.
- In order to listen to a public group channel, a client must subscribe to the channel name.
The sender of a message is derived from the message's signature.
- Discovery of channel names is not currently part of the protocol, and is typically done out of band.
If a channel name is used that has not been used, it will be created.
- A client MUST sign the message otherwise it will be discarded by the recipients.
- channel name specification:
- matches `[a-z0-9\-]`
- is not a public key
#### Private 1:1 messages
This can be done in the following ways:
1. scanning a user generated QR code
1. discovery through the Status app
1. asynchronous X3DH key exchange
1. public key via public channel listening
- `status-mobile/src/status_im/contact_code/core.cljs`
1. contact codes
1. decentralized storage (not implemented)
1. Whisper/Waku
### Initial Key Exchange
#### Bundles
- An X3DH prekey bundle is defined as ([code](https://github.com/status-im/status-go/messaging/chat/protobuf/encryption.pb.go)):
```golang
Identity // Identity key
SignedPreKeys // a map of installation id to array of signed prekeys by that installation id
Signature // Prekey signature
Timestamp // When the bundle was lasted created locally
```
- include BundleContainer
- a new bundle SHOULD be created at least every 12 hours
- a node only generates a bundle when it is used
- a bundle SHOULD be distributed on the contact code channel. This is the Whisper and Waku topic `{IK}-contact-code`,
where `IK` is the hex encoded public key of the user, prefixed with `0x`.
The node encrypts the channel in the same way it encrypted public chats.
### Contact Verification
To verify that contact key information is as it should be, use the following.
#### Identicon
A low-poly identicon is deterministically generated from the Whisper/Waku chat public key.
This can be compared out of band to ensure the receiver's public key is the one stored locally.
#### 3 word pseudonym / Whisper/Waku key fingerprint
Status generates a deterministic 3-word random pseudonym from the Whisper/Waku chat public key.
This pseudonym acts as a human readable fingerprint to the Whisper/Waku chat public key.
This name also shows when viewing a contact's public profile and in the chat UI.
- implementation: [gfycat](https://github.com/status-im/status-mobile/tree/develop/src/status_im/utils/gfycat)
#### ENS name
Status offers the ability to register a mapping of a human readable subdomain of `stateofus.eth` to their Whisper/Waku chat public key.
The user purchases this registration (currently by staking 10 SNT)
and the node stores it on the Ethereum mainnet blockchain for public lookup.
<!-- TODO: Elaborate on security implications -->
<!-- TODO: Incorporate or cut below into proper spec
### Possible Connection Breakdown
possible connections
- client - client (not really ever, this is facilitated through all other connections)
- personal chat
- ratcheted with X3DH
- private group chat
- pairwise ratcheted with X3DH
- public chat
- client - mailserver (statusd + ???)
- a mailserver identifies itself by an [enode address](https://github.com/ethereum/wiki/wiki/enode-url-format)
- client - Whisper/Waku node (statusd)
- a node identifies itself by an enode address
- client - bootnode (go-ethereum)
- a bootnode identifies itself by
- an enode address
- `NOTE: redezvous information here`
- client - ENS registry (ethereum blockchain -> default to infura)
- client - Ethereum RPC (custom go-ethereum RPC API -> default to infura API)
- client - IPFS (Status hosted IPFS gateway -> defaults to ???)
- we have a status hosted IPFS gateway for pinning but it currently isn't used much.
### Notes
A user in the system is a public-private key pair using the Elliptic-Curve Cryptography secp256k1 that Ethereum uses.
- A 3-word random name is derived from the public key using the following package
- `NOTE: need to find package`
- This provides an associated human-readble fingerprint to the user's public key
- A user can optionally add additional layers on top of this keypair
- Chosen username
- ENS username
All messages sent are encrypted with the public key of the destination and signed by the private key of the given user using the following scheme:
- private chat
- X3DH is used to define shared secrets which is then double ratcheted
- private group chat
- considered pairwise private chats
- public group chat
- the message is encrypted with a symmetric key derived from the chat name
-->
## Public Key Serialization
Idiomatically known as "public key compression" and "public key decompression".
The node SHOULD provide functionality for the serialization and deserialization of public / chat keys.
For maximum flexibility, when implementing this functionality, the node MUST support public keys encoded in a range of encoding formats, detailed below.
### Basic Serialization Example
In the example of a typical hexadecimal encoded elliptical curve (EC) public key (such as a secp256k1 pk),
```text
0x04261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc3cd4e22200c68daf7493e1f8da6a190a68a671e2d3977809612424c7c3888bc6
```
minor modification for compatibility and flexibility makes the key self-identifiable and easily parsable,
```text
fe70104261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc3cd4e22200c68daf7493e1f8da6a190a68a671e2d3977809612424c7c3888bc6
```
EC serialization and compact encoding produces a much smaller string representation of the original key.
```text
zQ3shPyZJnxZK4Bwyx9QsaksNKDYTPmpwPvGSjMYVHoXHeEgB
```
### Public Key "Compression" Rationale
Serialized and compactly encoded ("compressed") public keys have a number of UI / UX advantages
over non-serialized less densely encoded public keys.
Compressed public keys are smaller, and users may perceive them as less intimidating and less unnecessarily large.
Compare the "compressed" and "uncompressed" version of the same public key from above example:
- `0xe70104261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc3cd4e22200c68daf7493e1f8da6a190a68a671e2d3977809612424c7c3888bc6`
- `zQ3shPyZJnxZK4Bwyx9QsaksNKDYTPmpwPvGSjMYVHoXHeEgB`
The user can transmit and share the same data, but at one third of the original size.
136 characters uncompressed vs 49 characters compressed, giving a significant character length reduction of 64%.
The user client app MAY use the compressed public keys throughout the user interface.
For example in the `status-mobile` implementation of the user interface
the following places could take advantage of a significantly smaller public key:
- `Onboarding` > `Choose a chat name`
- `Profile` > `Header`
- `Profile` > `Share icon` > `QR code popover`
- `Invite friends` url from `Invite friends` button and `+ -button` > `Invite friends`
- Other user `Profile details`
- `Profile details` > `Share icon` > `QR code popover`
In the case of QR codes a compressed public key can reduce the complexity of the derived codes:
| Uncompressed | Compressed |
| --- | --- |
|![image](/status/deprecated/images/qr-code1-accountmd.png)|![image](/status/deprecated/images/qr-code2-accountmd.png)|
### Key Encoding
When implementing the pk de/serialization functionality, the node MUST use the [multiformats/multibase](https://github.com/multiformats/multibase)
encoding protocol to interpret incoming key data and to return key data in a desired encoding.
The node SHOULD support the following `multibase` encoding formats.
```csv
encoding, code, description, status
identity, 0x00, 8-bit binary (encoder and decoder keeps data unmodified), default
base2, 0, binary (01010101), candidate
base8, 7, octal, draft
base10, 9, decimal, draft
base16, f, hexadecimal, default
base16upper, F, hexadecimal, default
base32hex, v, rfc4648 case-insensitive - no padding - highest char, candidate
base32hexupper, V, rfc4648 case-insensitive - no padding - highest char, candidate
base32hexpad, t, rfc4648 case-insensitive - with padding, candidate
base32hexpadupper, T, rfc4648 case-insensitive - with padding, candidate
base32, b, rfc4648 case-insensitive - no padding, default
base32upper, B, rfc4648 case-insensitive - no padding, default
base32pad, c, rfc4648 case-insensitive - with padding, candidate
base32padupper, C, rfc4648 case-insensitive - with padding, candidate
base32z, h, z-base-32 (used by Tahoe-LAFS), draft
base36, k, base36 [0-9a-z] case-insensitive - no padding, draft
base36upper, K, base36 [0-9a-z] case-insensitive - no padding, draft
base58btc, z, base58 bitcoin, default
base58flickr, Z, base58 flicker, candidate
base64, m, rfc4648 no padding, default
base64pad, M, rfc4648 with padding - MIME encoding, candidate
base64url, u, rfc4648 no padding, default
base64urlpad, U, rfc4648 with padding, default
```
**Note** this specification RECOMMENDs that implementations extend the standard `multibase` protocol
to parse strings prepended with `0x` as `f` hexadecimal encoded bytes.
Implementing this recommendation will allow the node to correctly interpret traditionally identified hexadecimal strings (e.g. `0x1337c0de`).
*Example:*
`0xe70102261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc`
SHOULD be interpreted as
`fe70102261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc`
This specification RECOMMENDs that the consuming service of the node uses a compact encoding type,
such as base64 or base58 to allow for as short representations of the key as possible.
### Public Key Types
When implementing the pk de/serialization functionality, The node MUST support the [multiformats/multicodec](https://github.com/multiformats/multicodec) key type identifiers for the following public key type.
| Name | Tag | Code | Description |
| ------------------ | --- | ------ | ------------------------------------ |
| `secp256k1-pub` | key | `0xe7` | Secp256k1 public key |
For a public key to be identifiable to the node the public key data MUST be prepended with the relevant [multiformats/unsigned-varint](https://github.com/multiformats/unsigned-varint) formatted code.
*Example:*
Below is a representation of an deserialized secp256k1 public key.
```text
04
26 | 1c | 55 | 67 | 5e | 55 | ff | 25
ed | b5 | 0b | 34 | 5c | fb | 3a | 3f
35 | f6 | 07 | 12 | d2 | 51 | cb | aa
ab | 97 | bd | 50 | 05 | 4c | 6e | bc
3c | d4 | e2 | 22 | 00 | c6 | 8d | af
74 | 93 | e1 | f8 | da | 6a | 19 | 0a
68 | a6 | 71 | e2 | d3 | 97 | 78 | 09
61 | 24 | 24 | c7 | c3 | 88 | 8b | c6
```
The `multicodec` code for a secp256k1 public key is `0xe7`.
After parsing the code `0xe7` as a `multiformats/uvarint`, the byte value is `0xe7 0x01`, prepending this to the public key results in the below representation.
```text
e7 | 01 | 04
26 | 1c | 55 | 67 | 5e | 55 | ff | 25
ed | b5 | 0b | 34 | 5c | fb | 3a | 3f
35 | f6 | 07 | 12 | d2 | 51 | cb | aa
ab | 97 | bd | 50 | 05 | 4c | 6e | bc
3c | d4 | e2 | 22 | 00 | c6 | 8d | af
74 | 93 | e1 | f8 | da | 6a | 19 | 0a
68 | a6 | 71 | e2 | d3 | 97 | 78 | 09
61 | 24 | 24 | c7 | c3 | 88 | 8b | c6
```
### De/Serialization Process Flow
When implementing the pk de/serialization functionality, the node MUST be passed a `multicodec` identified public key,
of the above supported types, encoded with a valid `multibase` identifier.
This specification RECOMMENDs that the node also accept an encoding type parameter to encode the output data.
This provides for the case where the user requires the de/serialization key to be in a different encoding to the encoding of the given key.
#### Serialization Example
A hexadecimal encoded secp256k1 public chat key typically is represented as below:
```text
0x04261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc3cd4e22200c68daf7493e1f8da6a190a68a671e2d3977809612424c7c3888bc6
```
To be properly interpreted by the node for serialization the public key MUST be prepended with the `multicodec` `uvarint` code `0xea 0x01`
and encoded with a valid `multibase` encoding, therefore giving the following:
```text
fea0104261c55675e55ff25edb50b345cfb3a3f35f60712d251cbaaab97bd50054c6ebc3cd4e22200c68daf7493e1f8da6a190a68a671e2d3977809612424c7c3888bc6
```
If adhering to the specification recommendation to provide the user with an output encoding parameter,
the above string would be passed to the node with the following `multibase` encoding identifier.
In this example the output encoding is defined as `base58 bitcoin`.
```text
z
```
The return value in this case would be
```text
zQ3shPyZJnxZK4Bwyx9QsaksNKDYTPmpwPvGSjMYVHoXHeEgB
```
Which after `multibase` decoding can be represented in bytes as below:
```text
e7 | 01 | 02
26 | 1c | 55 | 67 | 5e | 55 | ff | 25
ed | b5 | 0b | 34 | 5c | fb | 3a | 3f
35 | f6 | 07 | 12 | d2 | 51 | cb | aa
ab | 97 | bd | 50 | 05 | 4c | 6e | bc
```
#### Deserialization Example
For the user, the deserialization process is exactly the same as serialization with the exception
that the user MUST provide a serialized public key for deserialization. Else the deserialization algorithm will fail.
For further guidance on the implementation of public key de/serialization consult the [`status-go` implementation and tests](https://github.com/status-im/status-go/blob/c9772325f2dca76b3504191c53313663ca2efbe5/api/utils_test.go).
## Security Considerations
-
## Changelog
### Version 0.4
Released [June 24, 2020](https://github.com/status-im/specs/commit/e98a9b76b7d4e1ce93e0b692e1521c2d54f72c59)
- Added details of public key serialization and deserialization
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
- Added language to include Waku in all relevant places
- Change to keep `Mailserver` term consistent
- Added clarification to Open Whisper Systems
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
- [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)
- [EIP1581](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1581.md)
- [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
- [Open Whisper Systems](https://en.wikipedia.org/wiki/Signal_Messenger#2013%E2%80%932018:_Open_Whisper_Systems)
- [X3DH](https://signal.org/docs/specifications/x3dh/#the-x3dh-protocol)
- [web3 API](https://web3js.readthedocs.io/en/1.0/web3-shh.html#generatesymkeyfrompassword)
- [Protobuf encryption](https://github.com/status-im/status-go/messaging/chat/protobuf/encryption.pb.go)
- [gfycat in Status](https://github.com/status-im/status-mobile/tree/develop/src/status_im/utils/gfycat)
- [multiformats](https://github.com/multiformats/)
- [status-go implementation and tests](https://github.com/status-im/status-go/blob/c9772325f2dca76b3504191c53313663ca2efbe5/api/utils_test.go)
- [June 24, 2020 change commit](https://github.com/status-im/specs/commit/e98a9b76b7d4e1ce93e0b692e1521c2d54f72c59)
- [May 22, 2020 change commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)

427
status/deprecated/client.md Normal file
View File

@@ -0,0 +1,427 @@
---
title: CLIENT
name: Client
status: deprecated
description: This specification describes how to write a Status client for communicating with other Status clients.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Andrea Maria Piana <andreap@status.im>
- Dean Eigenmann <dean@status.im>
- Corey Petty <corey@status.im>
- Oskar Thorén <oskar@status.im>
- Samuel Hawksby-Robinson <samuel@status.im>
---
## Abstract
This specification describes how to write a Status client for communicating
with other Status clients.
This specification presents a reference implementation of the protocol
used in a command-line client and a mobile app.
This document consists of two parts.
The first outlines the specifications required to be a full Status client.
The second provides a design rationale and answers some common questions.
## Introduction
### Protocol layers
Implementing a Status clients largely means implementing the following layers.
Additionally, there are separate specifications for things like key management and account lifecycle.
Other aspects, such as how a node uses IPFS for stickers or how the browser works, are currently underspecified.
These specifications facilitate the implementation of a Status client for basic private communication.
| Layer | Purpose | Technology |
| ----------------- | ------------------------------ | ---------------------------- |
| Data and payloads | End user functionality | 1:1, group chat, public chat |
| Data sync | Data consistency | MVDS. |
| Secure transport | Confidentiality, PFS, etc | Double Ratchet |
| Transport privacy | Routing, Metadata protection | Waku / Whisper |
| P2P Overlay | Overlay routing, NAT traversal | devp2p |
### Protobuf
[`protobuf`](https://developers.google.com/protocol-buffers/) is used in different layers, version `proto3` used is unless stated otherwise.
## Components
### P2P Overlay
Status clients run on a public, permissionless peer-to-peer network, as specified by the devP2P
network protocols. devP2P provides a protocol for node discovery which is in
draft mode
[here](https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md). See
more on node discovery and management in the next section.
To communicate between Status nodes, the [RLPx Transport
Protocol, v5](https://github.com/ethereum/devp2p/blob/master/rlpx.md) is used, which
allows for TCP-based communication between nodes.
On top of this RLPx-based subprotocols are ran, the client
SHOULD NOT use [Whisper V6](https://eips.ethereum.org/EIPS/eip-627), the client
SHOULD use [Waku V1](/waku/standards/legacy/6/waku1.md)
for privacy-preserving messaging and efficient usage of a node's bandwidth.
#### Node discovery and roles
There are four types of node roles:
1. `Bootstrap node`
1. `Whisper/Waku relayer`
1. `Mailserver` (servers and clients)
1. `Mobile node` (Status Clients)
A standard Status client MUST implement both `Whisper/Waku relayer` and `Mobile node` node types. The
other node types are optional, but it is RECOMMEND to implement a `Mailserver`
client mode, otherwise the user experience is likely to be poor.
#### Bootstrapping
Bootstrap nodes allow Status nodes to discover and connect to other Status nodes
in the network.
Currently, Status Gmbh provides the main bootstrap nodes, but anyone can
run these provided they are connected to the rest of the Whisper/Waku network.
Status maintains a list of production fleet bootstrap nodes in the following locations:
**Hong Kong:**
- `enode://6e6554fb3034b211398fcd0f0082cbb6bd13619e1a7e76ba66e1809aaa0c5f1ac53c9ae79cf2fd4a7bacb10d12010899b370c75fed19b991d9c0cdd02891abad@47.75.99.169:443`
- `enode://23d0740b11919358625d79d4cac7d50a34d79e9c69e16831c5c70573757a1f5d7d884510bc595d7ee4da3c1508adf87bbc9e9260d804ef03f8c1e37f2fb2fc69@47.52.106.107:443`
**Amsterdam:**
- `enode://436cc6f674928fdc9a9f7990f2944002b685d1c37f025c1be425185b5b1f0900feaf1ccc2a6130268f9901be4a7d252f37302c8335a2c1a62736e9232691cc3a@178.128.138.128:443`
- `enode://5395aab7833f1ecb671b59bf0521cf20224fe8162fc3d2675de4ee4d5636a75ec32d13268fc184df8d1ddfa803943906882da62a4df42d4fccf6d17808156a87@178.128.140.188:443`
**Central US:**
- `enode://32ff6d88760b0947a3dee54ceff4d8d7f0b4c023c6dad34568615fcae89e26cc2753f28f12485a4116c977be937a72665116596265aa0736b53d46b27446296a@34.70.75.208:443`
- `enode://5405c509df683c962e7c9470b251bb679dd6978f82d5b469f1f6c64d11d50fbd5dd9f7801c6ad51f3b20a5f6c7ffe248cc9ab223f8bcbaeaf14bb1c0ef295fd0@35.223.215.156:443`
These bootstrap nodes MAY change and are not guaranteed to stay this way forever
and at some point circumstances might force them to change.
#### Discovery
A Status client MUST discover or have a list of peers to connect to. Status uses a
light discovery mechanism based on a combination of [Discovery v5](https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md) and
[Rendezvous Protocol](https://github.com/libp2p/specs/tree/master/rendezvous),
(with some [modifications](https://github.com/status-im/rendezvous#differences-with-original-rendezvous)).
Additionally, some static nodes MAY also be used.
A Status client MUST use at least one discovery method or use static nodes
to communicate with other clients.
Discovery V5 uses bootstrap nodes to discover other peers. Bootstrap nodes MUST support
Discovery V5 protocol as well in order to provide peers. It is kademlia-based discovery mechanism
and it might consume significant (at least on mobile) amount of network traffic to operate.
In order to take advantage from simpler and more mobile-friendly peers discovery mechanism,
i.e. Rendezvous protocol, one MUST provide a list of Rendezvous nodes which speak
Rendezvous protocol. Rendezvous protocol is request-response discovery mechanism.
It uses Ethereum Node Records (ENR) to report discovered peers.
Both peers discovery mechanisms use topics to provide peers with certain capabilities.
There is no point in returning peers that do not support a particular protocol.
Status nodes that want to be discovered MUST register to Discovery V5 and/or Rendezvous
with the `whisper` topic. Status nodes that are `Mailservers` and want to
be discoverable MUST additionally register with the `whispermail` topic.
It is RECOMMENDED to use both mechanisms but at the same time implement a structure
called `PeerPool`. `PeerPool` is responsible for maintaining an optimal number of peers.
For mobile nodes, there is no significant advantage to have more than 2-3 peers and one `Mailserver`.
`PeerPool` can notify peers discovery protocol implementations that they should suspend
their execution because the optimal number of peers is found. They should resume
if the number of connected peers drops or a `Mailserver` disconnects.
It is worth noticing that an efficient caching strategy MAY be of great use, especially,
on mobile devices. Discovered peers can be cached as they rarely change and used
when the client starts again. In such a case, there might be no need to even start
peers discovery protocols because cached peers will satisfy the optimal number of peers.
Alternatively, a client MAY rely exclusively on a list of static peers. This is the most efficient
way because there are no peers discovery algorithm overhead introduced. The disadvantage
is that these peers might be gone and without peers discovery mechanism, it won't be possible to find
new ones.
The current list of static peers is published on <https://fleets.status.im/>. `eth.prod` is the current
group of peers the official Status client uses. The others are test networks.
Finally, Waku node addresses can be retrieved by traversing
the merkle tree found at [`fleets.status.im`](https://fleets.status.im), as described in [EIP-1459](https://eips.ethereum.org/EIPS/eip-1459#client-protocol).
#### Mobile nodes
A `Mobile node` is a Whisper and/or Waku node which connects to part of the respective Whisper
and/or Waku network(s). A `Mobile node` MAY relay messages. See next section for more details on how
to use Whisper and/or Waku to communicate with other Status nodes.
### Transport privacy and Whisper / Waku usage
Once a Whisper and/or Waku node is up and running there are some specific settings required
to communicate with other Status nodes.
See [WHISPER-USAGE](/status/deprecated/whisper-usage.md) and [WAKU-USAGE](/status/deprecated/waku-usage.md) for more details.
For providing an offline inbox, see the complementary [WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md) and [WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md).
### Secure Transport
In order to provide confidentiality, integrity, authentication and forward
secrecy of messages the node implements a secure transport on top of Whisper and Waku. This is
used in 1:1 chats and group chats, but not for public chats. See [SECURE-TRANSPORT](/status/deprecated/secure-transport.md) for more.
### Data Sync
[MVDS](/vac/2/mvds.md) is used for 1:1 and group chats, however it is currently not in use for public chats.
[Status payloads](#payloads-and-clients) are serialized and then wrapped inside an
MVDS message which is added to an [MVDS payload](/vac/2/mvds.md#payloads),
the node encrypts this payload (if necessary for 1-to-1 / group-chats) and sends it using
Whisper or Waku which also encrypts it.
### Payloads and clients
On top of secure transport, various types of data sync clients and
the node uses payload formats for things like 1:1 chat, group chat and public chat. These have
various degrees of standardization. Please refer to [PAYLOADS](/status/deprecated/payloads.md) for more details.
### BIPs and EIPs Standards support
For a list of EIPs and BIPs that SHOULD be supported by Status client, please
see [EIPS](/status/deprecated/eips.md).
## Security Considerations
See [Appendix A](#appendix-a-security-considerations)
## Design Rationale
P2P Overlay
### Why devp2p? Why not use libp2p?
At the time Status developed the main Status clients, devp2p was the most
mature. However, in the future libp2p is likely to be used, as it'll
provide us with multiple transports, better protocol negotiation, NAT traversal,
etc.
For very experimental bridge support, see the bridge between libp2p and devp2p
in [Murmur](https://github.com/status-im/murmur).
### What about other RLPx subprotocols like LES, and Swarm?
Status is primarily optimized for resource restricted devices, and at present
time light client support for these protocols are suboptimal. This is a work in
progress.
For better Ethereum light client support, see [Re-enable LES as
option](https://github.com/status-im/status-go/issues/1025). For better Swarm
support, see [Swarm adaptive
nodes](https://github.com/ethersphere/SWIPs/pull/12).
For transaction support, Status clients currently have to rely on Infura.
Status clients currently do not offer native support for file storage.
### Why do you use Whisper?
Whisper is one of the [three parts](http://gavwood.com/dappsweb3.html) of the
vision of Ethereum as the world computer, Ethereum and Swarm being the other
two. Status was started as an encapsulation of and a clear window to this world
computer.
### Why do you use Waku?
Waku is a direct upgrade and replacement for Whisper, the main motivation for
developing and implementing Waku can be found in the [Waku specs](/waku/).
>Waku was created to incrementally improve in areas that Whisper is lacking in,
>with special attention to resource restricted devices. We specify the standard for
>Waku messages in order to ensure forward compatibility of different Waku clients,
>backwards compatibility with Whisper clients, as well as to allow multiple
>implementations of Waku and its capabilities. We also modify the language to be more
>unambiguous, concise and consistent.
Considerable work has gone into the active development of Ethereum, in contrast Whisper
is not currently under active development, and it has several drawbacks. Among others:
- Whisper is very wasteful bandwidth-wise and doesn't appear to be scalable
- Proof of work is a poor spam protection mechanism for heterogeneous devices
- The privacy guarantees provided are not rigorous
- There are no incentives to run a node
Finding a more suitable transport privacy is an ongoing research effort,
together with [Vac](https://vac.dev/vac-overview) and other teams in the space.
### Why is PoW for Waku set so low?
A higher PoW would be desirable, but this kills the battery on mobile phones,
which is a prime target for Status clients.
This means the network is currently vulnerable to DDoS attacks. Alternative
methods of spam protection are currently being researched.
### Why do you not use Discovery v5 for node discovery?
At the time of implementing dynamic node discovery, Discovery v5 wasn't completed
yet. Additionally, running a DHT on a mobile leads to slow node discovery, bad
battery and poor bandwidth usage. Instead, each client can choose to turn on
Discovery v5 for a short period until the node populates their peer list.
For some further investigation, see
[here](https://github.com/status-im/swarms/blob/master/ideas/092-disc-v5-research.md).
### I heard something about `Mailservers` being trusted somehow?
In order to use a `Mailserver`, a given node needs to connect to it directly, i.e. add the `Mailserver`
as its peer and mark it as trusted.
This means that the `Mailserver` is able to send direct p2p messages to the node instead of broadcasting them.
Effectively, it knows the bloom filter of the topics the node is interested in,
when it is online as well as many metadata like IP address.
### Data sync
#### Why is MVDS not used for public chats?
Currently, public chats are broadcast-based, and there's no direct way of finding
out who is receiving messages. Hence there's no clear group sync state context
whereby participants can sync. Additionally, MVDS is currently not optimized for
large group contexts, which means bandwidth usage will be a lot higher than
reasonable. See [P2P Data Sync for Mobile](https://vac.dev/p2p-data-sync-for-mobile) for more.
This is an active area of research.
## Footnotes
1. <https://github.com/status-im/status-protocol-go/>
2. <https://github.com/status-im/status-console-client/>
3. <https://github.com/status-im/status-mobile/>
## Appendix A: Security considerations
There are several security considerations to take into account when running Status.
Chief among them are: scalability, DDoS-resistance and privacy.
These also vary depending on what capabilities are used, such as `Mailserver`, light node, and so on.
### Scalability and UX
**Bandwidth usage:**
In version 1 of Status, bandwidth usage is likely to be an issue.
In Status version 1.1 this is partially addressed with Waku usage, see [the theoretical scaling model](https://github.com/vacp2p/research/tree/dcc71f4779be832d3b5ece9c4e11f1f7ec24aac2/whisper_scalability).
**`Mailserver` High Availability requirement:**
A `Mailserver` has to be online to receive messages for other nodes, this puts a high availability requirement on it.
**Gossip-based routing:**
Use of gossip-based routing doesn't necessarily scale.
It means each node can see a message multiple times,
and having too many light nodes can cause propagation probability that is too low.
See [Whisper vs PSS](https://our.status.im/whisper-pss-comparison/) for more and a possible Kademlia based alternative.
**Lack of incentives:**
Status currently lacks incentives to run nodes, which means node operators are more likely to create centralized choke points.
### Privacy
**Light node privacy:**
The main privacy concern with light nodes is that directly connected peers will know that a message originates from them (as it are the only ones it sends). This means nodes can make assumptions about what messages (topics) their peers are interested in.
**Bloom filter privacy:**
A user reveals which messages they are interested in, by setting only the topics they are interested in on the bloom filter.
This is a fundamental trade-off between bandwidth usage and privacy,
though the trade-off space is likely suboptimal in terms of the [Anonymity](https://eprint.iacr.org/2017/954.pdf) [trilemma](https://petsymposium.org/2019/files/hotpets/slides/coordination-helps-anonymity-slides.pdf).
**`Mailserver client` privacy:**
A `Mailserver client` has to trust a `Mailserver`, which means they can send direct traffic. This reveals what topics / bloom filter a node is interested in, along with its peerID (with IP).
**Privacy guarantees not rigorous:**
Privacy for Whisper or Waku hasn't been studied rigorously for various threat models like global passive adversary, local active attacker, etc. This is unlike e.g. Tor and mixnets.
**Topic hygiene:**
Similar to bloom filter privacy, using a very specific topic reveals more information. See scalability model linked above.
### Spam resistance
**PoW bad for heterogeneous devices:**
Proof of work is a poor spam prevention mechanism. A mobile device can only have a very low PoW in order not to use too much CPU / burn up its phone battery. This means someone can spin up a powerful node and overwhelm the network.
**`Mailserver` trusted connection:**
A `Mailserver` has a direct TCP connection, which means they are trusted to send traffic. This means a malicious or malfunctioning `Mailserver` can overwhelm an individual node.
### Censorship resistance
**Devp2p TCP port blockable:**
By default Devp2p runs on port `30303`, which is not commonly used for any other service. This means it is easy to censor, e.g. airport WiFi. This can be mitigated somewhat by running on e.g. port `80` or `443`, but there are still outstanding issues. See libp2p and Tor's Pluggable Transport for how this can be improved.
See <https://github.com/status-im/status-mobile/issues/6351> for some discussion.
## Acknowledgments
Jacek Sieka
## Changelog
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
- Added that Waku SHOULD be used
- Added that Whisper SHOULD NOT be used
- Added language to include Waku in all relevant places
- Change to keep `Mailserver` term consistent
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [Protobuf](https://developers.google.com/protocol-buffers/)
- [Discv5](https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md)
- [RLPx Transport Protocol, v5](https://github.com/ethereum/devp2p/blob/master/rlpx.md)
- [Whisper V6](https://eips.ethereum.org/EIPS/eip-627)
- [Waku V1](/waku/standards/legacy/6/waku1.md)
- [Rendezvous Protocol](https://github.com/libp2p/specs/tree/master/rendezvous)
- [Rendezvous Protocol modifications](https://github.com/status-im/rendezvous#differences-with-original-rendezvous)
- [Fleets Status](https://fleets.status.im)
- [EIP-1459](https://eips.ethereum.org/EIPS/eip-1459#client-protocol)
- [WHISPER-USAGE](/status/deprecated/whisper-usage.md)
- [WAKU-USAGE](/status/deprecated/waku-usage.md)
- [WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md)
- [WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md)
- [SECURE-TRANSPORT](/status/deprecated/secure-transport.md)
- [MVDS](/vac/2/mvds.md)
- [PAYLOADS](/status/deprecated/payloads.md)
- [EIPS](/status/deprecated/eips.md)
- [Murmur](https://github.com/status-im/murmur)
- [Re-enable LES as option](https://github.com/status-im/status-go/issues/1025)
- [Swarm adaptive nodes](https://github.com/ethersphere/SWIPs/pull/12)
- [Whisper vs PSS](https://our.status.im/whisper-pss-comparison/)
- [Waku specs](/waku/)
- [Vac](https://vac.dev/vac-overview)
- [theoretical scaling model](https://github.com/vacp2p/research/tree/dcc71f4779be832d3b5ece9c4e11f1f7ec24aac2/whisper_scalability)
- [Anonymity](https://eprint.iacr.org/2017/954.pdf)
- [trilemma](https://petsymposium.org/2019/files/hotpets/slides/coordination-helps-anonymity-slides.pdf)
- [Whisper vs PSS](https://our.status.im/whisper-pss-comparison/)
- [Discovery v5 research](https://github.com/status-im/swarms/blob/master/ideas/092-disc-v5-research.md)
- [P2P Data Sync for Mobile](https://vac.dev/p2p-data-sync-for-mobile)
- [Status protocol go](https://github.com/status-im/status-protocol-go/)
- [Status console client](https://github.com/status-im/status-console-client/)
- [Status mobile](https://github.com/status-im/status-mobile/)
- [Status mobile issue 6351](https://github.com/status-im/status-mobile/issues/6351)

View File

@@ -0,0 +1,135 @@
---
title: Dapp browser API usage
name: Dapp browser API usage
status: deprecated
description: This document describes requirements that an application must fulfill in order to provide a proper environment for Dapps running inside a browser.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
---
## Abstract
This document describes requirements that an application must fulfill in order to provide a proper environment for Dapps running inside a browser.
A description of the Status Dapp API is provided, along with an overview of bidirectional communication underlying the API implementation.
The document also includes a list of EIPs that this API implements.
## Definitions
| Term | Description |
|------------|-------------------------------------------------------------------------------------|
| **Webview** | Platform-specific browser core implementation. |
| **Ethereum Provider** | A JS object (`window.ethereum`) injected into each web page opened in the browser providing web3 compatible provider. |
| **Bridge** | A set of facilities allow bidirectional communication between JS code and the application. |
## Overview
The application should expose an Ethereum Provider object (`window.ethereum`) to JS code running inside the browser.
It is important to have the `window.ethereum` object available before the page loads, otherwise Dapps might not work correctly.
Additionally, the browser component should also provide bidirectional communication between JS code and the application.
## Usage in Dapps
Dapps can use the below properties and methods of `window.ethereum` object.
### Properties
#### `isStatus`
Returns true. Can be used by the Dapp to find out whether it's running inside Status.
#### `status`
Returns a `StatusAPI` object. For now it supports one method: `getContactCode` that sends a `contact-code` request to Status.
### Methods
#### `isConnected`
Similarly to Ethereum JS API [docs](https://github.com/ethereum/wiki/wiki/JavaScript-API#web3isconnected),
it should be called to check if connection to a node exists. On Status, this fn always returns true, as once Status is up and running, node is automatically started.
#### `scanQRCode`
Sends a `qr-code` Status API request.
#### `request`
`request` method as defined by EIP-1193.
### Unused
Below are some legacy methods that some Dapps might still use.
#### `enable` (DEPRECATED)
Sends a `web3` Status API request. It returns a first entry in the list of available accounts.
Legacy `enable` method as defined by [EIP1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md).
#### `send` (DEPRECATED)
Legacy `send` method as defined by [EIP1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md).
#### `sendAsync` (DEPRECATED)
Legacy `sendAsync` method as defined by [EIP1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md).
#### `sendSync` (DEPRECATED)
Legacy `send` method.
## Implementation
Status uses a [forked version](https://github.com/status-im/react-native-webview) of [react-native-webview](https://github.com/react-native-community/react-native-webview) to display web or dapps content.
The fork provides an Android implementation of JS injection before page load.
It is required in order to properly inject Ethereum Provider object.
Status injects two JS scripts:
- [provider.js](https://github.com/status-im/status-mobile/blob/develop/resources/js/provider.js): `window.ethereum` object
- [webview.js](https://github.com/status-im/status-mobile/blob/develop/resources/js/webview.js): override for `history.pushState` used internally
Dapps running inside a browser communicate with Status Ethereum node by means of a *bridge* provided by react-native-webview library.
The bridge allows for bidirectional communication between browser and Status. In order to do so, it injects a special `ReactNativeWebview` object into each page it loads.
On Status (React Native) end, `react-native-webview` library provides `WebView.injectJavascript` function
on a webview component that allows to execute arbitrary code inside the webview.
Thus it is possible to inject a function call passing Status node response back to the Dapp.
Below is the table briefly describing what functions/properties are used. More details available in package [docs](https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native).
| Direction | Side | Method |
|-----------|------|-----------|
| Browser->Status | JS | `ReactNativeWebView.postMessage()`|
| Browser->Status | RN | `WebView.onMessage()`|
| Status->Browser | JS | `ReactNativeWebView.onMessage()`|
| Status->Browser | RN | `WebView.injectJavascript()`|
## Compatibility
Status browser supports the following EIPs:
- [EIP1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md): `eth_requestAccounts` support
- [EIP1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md): `connect`, `disconnect`, `chainChanged`, and `accountsChanged` event support is not implemented
## Changelog
| Version | Comment |
| :-----: | ------- |
| 0.1.0 | Initial Release |
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [Ethereum JS API docs](https://github.com/ethereum/wiki/wiki/JavaScript-API#web3isconnected)
- [EIP1102](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md)
- [EIP1193](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md)
- [forked version](https://github.com/status-im/react-native-webview)
- [react-native-webview](https://github.com/react-native-community/react-native-webview)
- [provider.js](https://github.com/status-im/status-mobile/blob/develop/resources/js/provider.js)
- [webview.js](https://github.com/status-im/status-mobile/blob/develop/resources/js/webview.js)
- [docs](https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native)

286
status/deprecated/eips.md Normal file
View File

@@ -0,0 +1,286 @@
---
title: EIPS
name: EIPS
status: deprecated
description: Status relation with the EIPs
editor: Ricardo Guilherme Schmidt <ricardo3@status.im>
contributors:
-
---
## Abstract
This specification describes how Status relates with EIPs.
## Introduction
Status should follow all standards as possible.
Whenever the Status app needs a feature, it should be first checked if there is a standard for that,
if not, Status should propose a standard.
### Support table
| | Status v0 | Status v1 | Other | State |
|----------|-----------|-----------|----------| -------- |
| BIP32 | N | Y | N | `stable` |
| BIP39 | Y | Y | Y | `stable` |
| BIP43 | N | Y | N | `stable` |
| BIP44 | N | Y | N | `stable` |
| EIP20 | Y | Y | Y | `stable` |
| EIP55 | Y | Y | Y | `stable` |
| EIP67 | P | P | N | `stable` |
| EIP137 | P | P | N | `stable` |
| EIP155 | Y | Y | Y | `stable` |
| EIP165 | P | N | N | `stable` |
| EIP181 | P | N | N | `stable` |
| EIP191 | Y? | N | Y | `stable` |
| EIP627 | Y | Y | N | `stable` |
| EIP681 | Y | N | Y | `stable` |
| EIP712 | P | P | Y | `stable` |
| EIP721 | P | P | Y | `stable` |
| EIP831 | N | Y | N | `stable` |
| EIP945 | Y | Y | N | `stable` |
| EIP1102 | Y | Y | Y | `stable` |
| EIP1193 | Y | Y | Y | `stable` |
| EIP1577 | Y | P | N | `stable` |
| EIP1581 | N | Y | N | `stable` |
| EIP1459 | N | | N | `raw` |
## Components
### BIP32 - Hierarchical Deterministic Wallets
Support: Dependency.
[Reference](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
Description: Enable wallets to derive multiple private keys from the same seed.
Used for: Dependency of BIP39 and BIP43.
### BIP39 - Mnemonic code for generating deterministic keys
Support: Dependency.
[Reference](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)
Description: Enable wallet to create private key based on a safe seed phrase.
Used for: Security and user experience.
### BIP43 - Purpose Field for Deterministic Wallets
Support: Dependency.
[Reference](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
Description: Enable wallet to create private keys branched for a specific purpose.
Used for: Dependency of BIP44, uses "ethereum" coin.
### BIP44 - Multi-Account Hierarchy for Deterministic Wallets
Support: Dependency.
[Reference](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
Description: Enable wallet to derive multiple accounts in top of BIP39.
Used for: Privacy.
[Source code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/constants.cljs#L240)
Observation: BIP44 don't solve privacy issues regarding the transparency of transactions, therefore directly connected addresses through a transactions can be identifiable by a "network reconnaissance attack" over transaction history, this attack together with leakage of information from centralized services, such as exchanges, would be fatal against the whole privacy of users, regardless of BIP44.
### EIP20 - Fungible Token
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-20)
Description: Enable wallets to use tokens based on smart contracts compliant with this standard.
Used for: Wallet feature.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs)
### EIP55 - Mixed-case checksum address encoding
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-55)
Description: Checksum standard that uses lowercase and uppercase inside address hex value.
Used for: Sanity check of forms using ethereum address.
[Related](https://github.com/status-im/status-mobile/issues/4959) [Also](https://github.com/status-im/status-mobile/issues/8707)
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip55.cljs)
### EIP67 - Standard URI scheme with metadata, value and byte code
Support: Partial.
[Reference](https://github.com/ethereum/EIPs/issues/67)
Description: A standard way of creating Ethereum URIs for various use-cases.
Used for: Legacy support.
[Issue](https://github.com/status-im/status-mobile/issues/875)
### EIP137 - Ethereum Domain Name Service - Specification
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-137)
Description: Enable wallets to lookup ENS names.
Used for: User experience, as a wallet and identity feature, usernames.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/ens.cljs#L86)
### EIP155 - Simple replay attack protection
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-155)
Description: Defined chainId parameter in the singed ethereum transaction payload.
Used for: Signing transactions, crucial to safety of users against replay attacks.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/core.cljs)
### EIP165 - Standard Interface Detection
Support: Dependency/Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-165)
Description: Standard interface for contract to answer if it supports other interfaces.
Used for: Dependency of ENS and EIP721.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip165.cljs)
### EIP181 - ENS support for reverse resolution of Ethereum addresses
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-181)
Description: Enable wallets to render reverse resolution of Ethereum addresses.
Used for: Wallet feature.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/ens.cljs#L86)
### EIP191 - Signed Message
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-191)
Description: Contract signature standard, adds an obligatory padding to signed message to differentiate from Ethereum Transaction messages.
Used for: Dapp support, security, dependency of ERC712.
### EIP627 - Whisper Specification
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-627)
Description: format of Whisper messages within the ÐΞVp2p Wire Protocol.
Used for: Chat protocol.
### EIP681 - URL Format for Transaction Requests
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-681)
Description: A link that pop up a transaction in the wallet.
Used for: Useful as QR code data for transaction requests, chat transaction requests and for dapp links to transaction requests.
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip681.cljs)
Related: [Issue #9183: URL Format for Transaction Requests (EIP681) is poorly supported](https://github.com/status-im/status-mobile/issues/9183) [Issue #9240](https://github.com/status-im/status-mobile/pull/9240) [Issue #9238](https://github.com/status-im/status-mobile/issues/9238) [Issue #7214](https://github.com/status-im/status-mobile/issues/7214) [Issue #7325](https://github.com/status-im/status-mobile/issues/7325) [Issue #8150](https://github.com/status-im/status-mobile/issues/8150)
### EIP712 - Typed Signed Message
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-712)
Description: Standardize types for contract signature, allowing users to easily inspect whats being signed.
Used for: User experience, security.
Related: [Isse #5461](https://github.com/status-im/status-mobile/issues/5461) [Commit](https://github.com/status-im/status-mobile/commit/ba37f7b8d029d3358c7b284f6a2383b9ef9526c9)
### EIP721 - Non Fungible Token
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-721)
Description: Enable wallets to use tokens based on smart contracts compliant with this standard.
Used for: Wallet feature.
Related: [Issue #8909](https://github.com/status-im/status-mobile/issues/8909)
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/erc721.cljs) [Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs)
### EIP945 - Web 3 QR Code Scanning API
Support: Full.
[Reference](https://github.com/ethereum/EIPs/issues/945)
Used for: Sharing contactcode, reading transaction requests.
Related: [Issue #5870](https://github.com/status-im/status-mobile/issues/5870)
### EIP1102 - Opt-in account exposure
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-1102)
Description: Allow users to opt-in the exposure of their ethereum address to dapps they browse.
Used for: Privacy, DApp support.
Related: [Issue #7985](https://github.com/status-im/status-mobile/issues/7985)
### EIP1193 - Ethereum Provider JavaScript API
Support: Full.
[Reference](https://eips.ethereum.org/EIPS/eip-1193)
Description: Allows dapps to recognize event changes on wallet.
Used for: DApp support.
Related: [Issue #7246](https://github.com/status-im/status-mobile/pull/7246)
### EIP1577 - contenthash field for ENS
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-1577)
Description: Allows users browse ENS domains using contenthash standard.
Used for: Browser, DApp support.
Related: [Isse #6688](https://github.com/status-im/status-mobile/issues/6688)
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/utils/contenthash.cljs) [Sourcecode](https://github.com/status-im/status-mobile/blob/develop/test/cljs/status_im/test/utils/contenthash.cljs#L5)
### EIP1581 - Non-wallet usage of keys derived from BIP-32 trees
Support: Partial.
[Reference](https://eips.ethereum.org/EIPS/eip-1581)
Description: Allow wallet to derive keys that are less sensible (non wallet).
Used for: Security (don't reuse wallet key) and user experience (don't request keycard every login).
Related: [Issue #9096](https://github.com/status-im/status-mobile/issues/9088) [Issue #9096](https://github.com/status-im/status-mobile/pull/9096)
[Sourcecode](https://github.com/status-im/status-mobile/blob/develop/src/status_im/constants.cljs#L242)
### EIP1459 - Node Discovery via DNS
Support: -
[Reference](https://eips.ethereum.org/EIPS/eip-1459)
Description: Allows the storing and retrieving of nodes through merkle trees stored in TXT records of a domain.
Used for: Finding Waku nodes.
Related: -
Sourcecode: -
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [BIP32 - Hierarchical Deterministic Wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
- [BIP39 - Mnemonic code for generating deterministic keys](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)
- [BIP43 - Purpose Field for Deterministic Wallets](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
- [BIP44 - Multi-Account Hierarchy for Deterministic Wallets](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
- [BIP44 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/constants.cljs#L240)
- [EIP20 - Fungible Token](https://eips.ethereum.org/EIPS/eip-20)
- [EIP20 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs)
- [EIP55 - Mixed-case checksum address encoding](https://eips.ethereum.org/EIPS/eip-55)
- [EIP55 Related Issue 4959](https://github.com/status-im/status-mobile/issues/4959)
- [EIP55 Related Issue 8707](https://github.com/status-im/status-mobile/issues/8707)
- [EIP55 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip55.cljs)
- [EIP67 - Standard URI scheme with metadata, value and byte code](https://github.com/ethereum/EIPs/issues/67)
- [EIP67 Related Issue 875](https://github.com/status-im/status-mobile/issues/875)
- [EIP137 - Ethereum Domain Name Service - Specification](https://eips.ethereum.org/EIPS/eip-137)
- [EIP137 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/ens.cljs#L86)
- [EIP155 - Simple replay attack protection](https://eips.ethereum.org/EIPS/eip-155)
- [EIP155 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/core.cljs)
- [EIP165 - Standard Interface Detection](https://eips.ethereum.org/EIPS/eip-165)
- [EIP165 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip165.cljs)
- [EIP181 - ENS support for reverse resolution of Ethereum addresses](https://eips.ethereum.org/EIPS/eip-181)
- [EIP181 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/ens.cljs#L86)
- [EIP191 - Signed Message](https://eips.ethereum.org/EIPS/eip-191)
- [EIP627 - Whisper Specification](https://eips.ethereum.org/EIPS/eip-627)
- [EIP681 - URL Format for Transaction Requests](https://eips.ethereum.org/EIPS/eip-681)
- [EIP681 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/eip681.cljs)
- [EIP681 Related Issue 9183](https://github.com/status-im/status-mobile/issues/9183)
- [EIP681 Related Issue 9240](https://github.com/status-im/status-mobile/pull/9240)
- [EIP681 Related Issue 9238](https://github.com/status-im/status-mobile/issues/9238)
- [EIP681 Related Issue 7214](https://github.com/status-im/status-mobile/issues/7214)
- [EIP681 Related Issue 7325](https://github.com/status-im/status-mobile/issues/7325)
- [EIP681 Related Issue 8150](https://github.com/status-im/status-mobile/issues/8150)
- [EIP712 - Typed Signed Message](https://eips.ethereum.org/EIPS/eip-712)
- [EIP712 Related Issue 5461](https://github.com/status-im/status-mobile/issues/5461)
- [EIP712 Related Commit](https://github.com/status-im/status-mobile/commit/ba37f7b8d029d3358c7b284f6a2383b9ef9526c9)
- [EIP721 - Non Fungible Token](https://eips.ethereum.org/EIPS/eip-721)
- [EIP721 Related Issue 8909](https://github.com/status-im/status-mobile/issues/8909)
- [EIP721 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/erc721.cljs)
- [EIP721 Source Code (Tokens)](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs)
- [EIP945 - Web 3 QR Code Scanning API](https://github.com/ethereum/EIPs/issues/945)
- [EIP945 Related Issue 5870](https://github.com/status-im/status-mobile/issues/5870)
- [EIP1102 - Opt-in account exposure](https://eips.ethereum.org/EIPS/eip-1102)
- [EIP1102 Related Issue 7985](https://github.com/status-im/status-mobile/issues/7985)
- [EIP1193 - Ethereum Provider JavaScript API](https://eips.ethereum.org/EIPS/eip-1193)
- [EIP1193 Related Issue 7246](https://github.com/status-im/status-mobile/pull/7246)
- [EIP1577 - contenthash field for ENS](https://eips.ethereum.org/EIPS/eip-1577)
- [EIP1577 Related Issue 6688](https://github.com/status-im/status-mobile/issues/6688)
- [EIP1577 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/utils/contenthash.cljs)
- [EIP1577 Test Source Code](https://github.com/status-im/status-mobile/blob/develop/test/cljs/status_im/test/utils/contenthash.cljs#L5)
- [EIP1581 - Non-wallet usage of keys derived from BIP-32 trees](https://eips.ethereum.org/EIPS/eip-1581)
- [EIP1581 Related Issue 9088](https://github.com/status-im/status-mobile/issues/9088)
- [EIP1581 Related Issue 9096](https://github.com/status-im/status-mobile/pull/9096)
- [EIP1581 Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/constants.cljs#L242)
- [EIP1459 - Node Discovery via DNS](https://eips.ethereum.org/EIPS/eip-1459)

View File

@@ -0,0 +1,237 @@
---
title: ETHEREUM-USAGE
name: Status interactions with the Ethereum blockchain
status: deprecated
description: All interactions that the Status client has with the Ethereum blockchain.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Andrea Maria Piana <andreap@status.im>
---
## Abstract
This specification documents all the interactions that the Status client has
with the [Ethereum](https://ethereum.org/developers/) blockchain.
## Background
All the interactions are made through [JSON-RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC).
Currently [Infura](https://infura.io/) is used.
The client assumes high-availability,
otherwise it will not be able to interact with the Ethereum blockchain.
Status nodes rely on these Infura nodes
to validate the integrity of the transaction and report a consistent history.
Key handling is described [here](/status/deprecated/account.md)
1. [Wallet](#wallet)
2. [ENS](#ens)
## Wallet
The wallet in Status has two main components:
1) Sending transactions
2) Fetching balance
In the section below are described the `RPC` calls made the nodes, with a brief
description of their functionality and how it is used by Status.
1.[Sending transactions](#sending-transactions)
- [EstimateGas](#estimategas)
- [PendingNonceAt](#pendingnonceat)
- [SuggestGasPrice](#suggestgasprice)
- [SendTransaction](#sendtransaction)
2.[Fetching balance](#fetching-balance)
- [BlockByHash](#blockbyhash)
- [BlockByNumber](#blockbynumber)
- [FilterLogs](#filterlogs)
- [HeaderByNumber](#headerbynumber)
- [NonceAt](#nonceat)
- [TransactionByHash](#transactionbyhash)
- [TransactionReceipt](#transactionreceipt)
### Sending transactions
#### EstimateGas
EstimateGas tries to estimate the gas needed to execute a specific transaction
based on the current pending state of the backend blockchain.
There is no guarantee that this is the true gas limit requirement
as other transactions may be added or removed by miners,
but it should provide a basis for setting a reasonable default.
```go
func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error)
```
[L499](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L499)
#### PendingNonceAt
`PendingNonceAt` returns the account nonce of the given account in the pending state.
This is the nonce that should be used for the next transaction.
```go
func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
```
[L440](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L440)
#### SuggestGasPrice
`SuggestGasPrice` retrieves the currently suggested gas price to allow a timely
execution of a transaction.
```go
func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error)
```
[L487](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L487)
#### SendTransaction
`SendTransaction` injects a signed transaction into the pending pool for execution.
If the transaction was a contract creation use the TransactionReceipt method to get the
contract address after the transaction has been mined.
```go
func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error
```
[L512](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L512)
### Fetching balance
A Status node fetches the current and historical [ECR20](https://eips.ethereum.org/EIPS/eip-20) and ETH balance for the user wallet address.
Collectibles following the [ERC-721](https://eips.ethereum.org/EIPS/eip-721) are also fetched if enabled.
A Status node supports by default the following [tokens](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs). Custom tokens can be added by specifying the `address`, `symbol` and `decimals`.
#### BlockByHash
`BlockByHash` returns the given full block.
It is used by status to fetch a given block which will then be inspected
for transfers to the user address, both tokens and ETH.
```go
func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
```
[L78](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L78)
#### BlockByNumber
`BlockByNumber` returns a block from the current canonical chain. If number is nil, the
latest known block is returned.
```go
func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
```
[L82](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L82)
#### FilterLogs
`FilterLogs` executes a filter query.
Status uses this function to filter out logs, using the hash of the block
and the address of interest, both inbound and outbound.
```go
func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error)
```
[L377](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L377)
#### NonceAt
`NonceAt` returns the account nonce of the given account.
```go
func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
```
[L366](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L366)
#### TransactionByHash
`TransactionByHash` returns the transaction with the given hash,
used to inspect those transactions made/received by the user.
```go
func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error)
```
[L202](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L202)
#### HeaderByNumber
`HeaderByNumber` returns a block header from the current canonical chain.
```go
func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
```
[L172](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L172)
#### TransactionReceipt
`TransactionReceipt` returns the receipt of a transaction by transaction hash.
It is used in status to check if a token transfer was made to the user address.
```go
func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
```
[L270](https://github.com/ethereum/go-ethereum/blob/26d271dfbba1367326dec38068f9df828d462c61/ethclient/ethclient.go#L270)
## ENS
All the interactions with `ENS` are made through the [ENS contract](https://github.com/ensdomains/ens)
For the `stateofus.eth` username, one can be registered through these [contracts](https://github.com/status-im/ens-usernames)
### Registering, releasing and updating
- [Registering a username](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L113)
- [Releasing a username](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L131)
- [Updating a username](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L174)
### Slashing
Usernames MUST be in a specific format, otherwise they MAY be slashed:
- They MUST only contain alphanumeric characters
- They MUST NOT be in the form `0x[0-9a-f]{5}.*` and have more than 12 characters
- They MUST NOT be in the [reserved list](https://github.com/status-im/ens-usernames/blob/47c4c6c2058be0d80b7d678e611e166659414a3b/config/ens-usernames/reservedNames.js)
- They MUST NOT be too short, this is dynamically set in the contract and can be checked against the [contract](https://github.com/status-im/ens-usernames/blob/master/contracts/registry/UsernameRegistrar.sol#L26)
- [Slash a reserved username](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L237)
- [Slash an invalid username](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L261)
- [Slash a username too similar to an address](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L215)
- [Slash a username that is too short](https://github.com/status-im/ens-usernames/blob/77d9394d21a5b6213902473b7a16d62a41d9cd09/contracts/registry/UsernameRegistrar.sol#L200)
ENS names are propagated through `ChatMessage` and `ContactUpdate` [payload](/status/deprecated/payloads.md).
A client SHOULD verify ens names against the public key of the sender on receiving the message against the [ENS contract](https://github.com/ensdomains/ens)
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [Ethereum Developers](https://ethereum.org/developers/)
- [JSON-RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC)
- [Infura](https://infura.io/)
- [Key Handling](/status/deprecated/account.md)
- [ERC-20 Token Standard](https://eips.ethereum.org/EIPS/eip-20)
- [ERC-721 Non-Fungible Token Standard](https://eips.ethereum.org/EIPS/eip-721)
- [Supported Tokens Source Code](https://github.com/status-im/status-mobile/blob/develop/src/status_im/ethereum/tokens.cljs)
- [go-ethereum](https://github.com/ethereum/go-ethereum/)
- [ENS Contract](https://github.com/ensdomains/ens)

View File

@@ -0,0 +1,162 @@
---
title: GROUP-CHAT
name: Group Chat
status: deprecated
description: This document describes the group chat protocol used by the Status application.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Andrea Piana <andreap@status.im>
---
## Abstract
This document describes the group chat protocol used by the Status application.
The node uses pairwise encryption among members so a message is exchanged
between each participant, similarly to a one-to-one message.
## Membership updates
The node uses membership updates messages to propagate group chat membership changes.
The protobuf format is described in the [PAYLOADS](/status/deprecated/payloads.md).
Below describes each specific field.
The protobuf messages are:
```protobuf
// MembershipUpdateMessage is a message used to propagate information
// about group membership changes.
message MembershipUpdateMessage {
// The chat id of the private group chat
string chat_id = 1;
// A list of events for this group chat, first 65 bytes are the signature, then is a
// protobuf encoded MembershipUpdateEvent
repeated bytes events = 2;
// An optional chat message
ChatMessage message = 3;
}
message MembershipUpdateEvent {
// Lamport timestamp of the event as described in [Status Payload Specs](status-payload-specs.md#clock-vs-timestamp-and-message-ordering)
uint64 clock = 1;
// List of public keys of the targets of the action
repeated string members = 2;
// Name of the chat for the CHAT_CREATED/NAME_CHANGED event types
string name = 3;
// The type of the event
EventType type = 4;
enum EventType {
UNKNOWN = 0;
CHAT_CREATED = 1; // See [CHAT_CREATED](#chat-created)
NAME_CHANGED = 2; // See [NAME_CHANGED](#name-changed)
MEMBERS_ADDED = 3; // See [MEMBERS_ADDED](#members-added)
MEMBER_JOINED = 4; // See [MEMBER_JOINED](#member-joined)
MEMBER_REMOVED = 5; // See [MEMBER_REMOVED](#member-removed)
ADMINS_ADDED = 6; // See [ADMINS_ADDED](#admins-added)
ADMIN_REMOVED = 7; // See [ADMIN_REMOVED](#admin-removed)
}
}
```
### Payload
`MembershipUpdateMessage`:
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | chat-id | `string` | The chat id of the chat where the change is to take place |
| 2 | events | See details | A list of events that describe the membership changes, in their encoded protobuf form |
| 3 | message | `ChatMessage` | An optional message, described in [Message](/status/deprecated/payloads.md/#message) |
`MembershipUpdateEvent`:
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | The clock value of the event |
| 2 | members | `[]string` | An optional list of hex encoded (prefixed with `0x`) public keys, the targets of the action |
| 3 | name | `name` | An optional name, for those events that make use of it |
| 4 | type | `EventType` | The type of event sent, described below |
### Chat ID
Each membership update MUST be sent with a corresponding `chatId`.
The format of this chat ID MUST be a string of [UUID](https://tools.ietf.org/html/rfc4122),
concatenated with the hex-encoded public key of the creator of the chat, joined by `-`.
This chatId MUST be validated by all clients, and MUST be discarded if it does not follow these rules.
### Signature
The node calculates the signature for each event by encoding each `MembershipUpdateEvent` in its protobuf representation
and prepending the bytes of the chatID, lastly the node signs the `Keccak256` of the bytes
using the private key by the author and added to the `events` field of MembershipUpdateMessage.
### Group membership event
Any `group membership` event received MUST be verified by calculating the signature as per the method described above.
The author MUST be extracted from it, if the verification fails the event MUST be discarded.
#### CHAT_CREATED
Chat `created event` is the first event that needs to be sent.
Any event with a clock value lower than this MUST be discarded.
Upon receiving this event a client MUST validate the `chatId`
provided with the updates and create a chat with identified by `chatId` and named `name`.
#### NAME_CHANGED
`admins` use a `name changed` event to change the name of the group chat.
Upon receiving this event a client MUST validate the `chatId` provided with the updates
and MUST ensure the author of the event is an admin of the chat, otherwise the event MUST be ignored.
If the event is valid the chat name SHOULD be changed to `name`.
#### MEMBERS_ADDED
`admins` use a `members added` event to add members to the chat.
Upon receiving this event a client MUST validate the `chatId`
provided with the updates and MUST ensure the author of the event is an admin of the chat, otherwise the event MUST be ignored.
If the event is valid a client MUST update the list of members of the chat who have not joined, adding the `members` received.
`members` is an array of hex encoded public keys.
#### MEMBER_JOINED
`members` use a `members joined` event to signal that they want to start receiving messages from this chat.
Upon receiving this event a client MUST validate the `chatId` provided with the updates.
If the event is valid a client MUST update the list of members of the chat who joined, adding the signer.
Any `message` sent to the group chat should now include the newly joined member.
#### ADMINS_ADDED
`admins` use an `admins added` event to add make other admins in the chat.
Upon receiving this event a client MUST validate the `chatId` provided with the updates,
MUST ensure the author of the event is an admin of the chat
and MUST ensure all `members` are already `members` of the chat, otherwise the event MUST be ignored.
If the event is valid a client MUST update the list of admins of the chat, adding the `members` received.
`members` is an array of hex encoded public keys.
#### MEMBER_REMOVED
`members` and/or `admins` use a `member-removed` event to leave or kick members of the chat.
Upon receiving this event a client MUST validate the `chatId` provided with the updates, MUST ensure that:
- If the author of the event is an admin, target can only be themselves or a non-admin member.
- If the author of the event is not an admin, the target of the event can only be themselves.
If the event is valid a client MUST remove the member from the list of `members`/`admins` of the chat,
and no further message should be sent to them.
#### ADMIN_REMOVED
`Admins` use an `admin-removed` event to drop admin privileges.
Upon receiving this event a client MUST validate the `chatId` provided with the updates,
MUST ensure that the author of the event is also the target of the event.
If the event is valid a client MUST remove the member from the list of `admins` of the chat.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [PAYLOADS](/status/deprecated/payloads.md)
- [UUID](https://tools.ietf.org/html/rfc4122)

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,303 @@
---
title: Keycard Usage for Wallet and Chat Keys
name: Keycard Usage for Wallet and Chat Keys
status: deprecated
description: In this specification, we describe how Status communicates with Keycard to create, store and use multiaccount.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Roman Volosovskyi <roman@status.im>
---
## Abstract
In this specification, we describe how Status communicates with Keycard to create, store and use multiaccount.
## Definitions
| Term | Description |
| ------------------ | -------------------------------------------------------- |
| Keycard Hardwallet | [https://keycard.tech/docs/](https://keycard.tech/docs/) |
| | |
## Multiaccount creation/restoring
### Creation and restoring via mnemonic
1. `status-im.hardwallet.card/get-application-info`
request: `nil`
response: `{"initialized?" false}`
2. `status-im.hardwallet.card/init-card`
request: `{:pin 123123}`
response:
```clojure
{"password" "nEJXqf6VWbqeC5oN",
"puk" "411810112887",
"pin" "123123"}
```
3. `status-im.hardwallet.card/get-application-info`
request: `nil`
response:
```clojure
{"free-pairing-slots" 5,
"app-version" "2.2",
"secure-channel-pub-key" "04e70d7af7d91b8cd23adbefdfc242c096adee6c1b5ad27a4013a8f926864c1a4f816b338238dc4a04226ab42f23672585c6dca03627885530643f1656ee69b025",
"key-uid" "",
"instance-uid" "9f149d438988a7af5e1a186f650c9328",
"paired?" false,
"has-master-key?" false,
"initialized?" true}
```
4. `status-im.hardwallet.card/pair`
params: `{:password "nEJXqf6VWbqeC5oN"}`
response: `AAVefVX0kPGsxnvQV5OXRbRTLGI3k8/S27rpsq/lZrVR` (`pairing`)
5. `status-im.hardwallet.card/generate-and-load-keys`
```clojure
{:mnemonic "lift mansion moment version card type uncle sunny lock gather nerve math",
:pairing "AAVefVX0kPGsxnvQV5OXRbRTLGI3k8/S27rpsq/lZrVR",
:pin "123123"}
```
response:
```clojure
{"whisper-address" "1f29a1a60c8a12f80c397a91c6ae0323f420e609",
"whisper-private-key" "123123123123123",
"wallet-root-public-key" "04eb9d01990a106a65a6dfaa48300f72aecfeabe502d9f4f7aeaccb146dc2f16e2dec81dcec0a1a52c1df4450f441a48c210e1a73777c0161030378df22e4ae015",
"encryption-public-key" "045ee42f012d72be74b31a28ce320df617e0cd5b9b343fad34fcd61e2f5dfa89ab23d880473ba4e95401a191764c7f872b7af92ea0d8c39462147df6f3f05c2a11",
"wallet-root-address" "132dd67ff47cc1c376879c474fd2afd0f1eee6de",
"whisper-public-key" "0450ad84bb95f32c64f4e5027cc11d1b363a0566a0cfc475c5653e8af9964c5c9b0661129b75e6e1bc6e96ba2443238e53e7f49f2c5f2d16fcf04aca4826765d46",
"address" "bf93eb43fea2ce94bf3a6463c16680b56aa4a08a",
"wallet-address" "7eee1060d8e4722d36c99f30ff8291caa3cfc40c",
"key-uid" "472d8436ccedb64bcbd897bed5895ec3458b306352e1bcee377df87db32ef2c2",
"wallet-public-key" "0495ab02978ea1f8b059140e0be5a87aad9b64bb7d9706735c47dda6e182fd5ca41744ca37583b9a10c316b01d4321d6c85760c61301874089acab041037246294",
"public-key" "0465d452d12171711f32bb931f9ea26fe1b88fe2511a7909a042b914fde10a99719136365d506e2d1694fc14627f9d557da33865efc6001da3942fc1d4d2469ca1",
"instance-uid" "9f149d438988a7af5e1a186f650c9328"}
```
### Multiaccount restoring via pairing
This flow is required in case if a user want to pair a card with an existing multiaccount on it.
1. `status-im.hardwallet.card/get-application-info`
request: `nil`
response:
```clojure
{"free-pairing-slots" 4,
"app-version" "2.2",
"secure-channel-pub-key" "04e70d7af7d91b8cd23adbefdfc242c096adee6c1b5ad27a4013a8f926864c1a4f816b338238dc4a04226ab42f23672585c6dca03627885530643f1656ee69b025",
"key-uid" "",
"instance-uid" "9f149d438988a7af5e1a186f650c9328",
"paired?" false,
"has-master-key?" false,
"initialized?" true}
```
2. `status-im.hardwallet.card/pair`
params: `{:password "nEJXqf6VWbqeC5oN"}`
response: `AAVefVX0kPGsxnvQV5OXRbRTLGI3k8/S27rpsq/lZrVR` (`pairing`)
3. `status-im.hardwallet.card/generate-and-load-keys`
```clojure
{:mnemonic "lift mansion moment version card type uncle sunny lock gather nerve math",
:pairing "AAVefVX0kPGsxnvQV5OXRbRTLGI3k8/S27rpsq/lZrVR",
:pin "123123"}
```
response:
```clojure
{"whisper-address" "1f29a1a60c8a12f80c397a91c6ae0323f420e609",
"whisper-private-key" "123123123123123123123",
"wallet-root-public-key" "04eb9d01990a106a65a6dfaa48300f72aecfeabe502d9f4f7aeaccb146dc2f16e2dec81dcec0a1a52c1df4450f441a48c210e1a73777c0161030378df22e4ae015",
"encryption-public-key" "045ee42f012d72be74b31a28ce320df617e0cd5b9b343fad34fcd61e2f5dfa89ab23d880473ba4e95401a191764c7f872b7af92ea0d8c39462147df6f3f05c2a11",
"wallet-root-address" "132dd67ff47cc1c376879c474fd2afd0f1eee6de",
"whisper-public-key" "0450ad84bb95f32c64f4e5027cc11d1b363a0566a0cfc475c5653e8af9964c5c9b0661129b75e6e1bc6e96ba2443238e53e7f49f2c5f2d16fcf04aca4826765d46",
"address" "bf93eb43fea2ce94bf3a6463c16680b56aa4a08a",
"wallet-address" "7eee1060d8e4722d36c99f30ff8291caa3cfc40c",
"key-uid" "472d8436ccedb64bcbd897bed5895ec3458b306352e1bcee377df87db32ef2c2",
"wallet-public-key" "0495ab02978ea1f8b059140e0be5a87aad9b64bb7d9706735c47dda6e182fd5ca41744ca37583b9a10c316b01d4321d6c85760c61301874089acab041037246294",
"public-key" "0465d452d12171711f32bb931f9ea26fe1b88fe2511a7909a042b914fde10a99719136365d506e2d1694fc14627f9d557da33865efc6001da3942fc1d4d2469ca1",
"instance-uid" "9f149d438988a7af5e1a186f650c9328"}
```
## Multiaccount unlocking
1. `status-im.hardwallet.card/get-application-info`
params:
```clojure
{:pairing nil, :on-success nil}
```
response:
```clojure
{"free-pairing-slots" 4,
"app-version" "2.2",
"secure-channel-pub-key" "04b079ac513d5e0ebbe9becbae1618503419f5cb59edddc7d7bb09ce0db069a8e6dec1fb40c6b8e5454f7e1fcd0bb4a0b9750256afb4e4390e169109f3ea3ba91d",
"key-uid" "a5424fb033f5cc66dce9cbbe464426b6feff70ca40aa952c56247aaeaf4764a9",
"instance-uid" "2268254e3ed7898839abe0b40e1b4200",
"paired?" false,
"has-master-key?" true,
"initialized?" true}
```
2. `status-im.hardwallet.card/get-keys`
params:
```clojure
{:pairing "ACEWbvUlordYWOE6M1Narn/AXICRltjyuKIAn4kkPXQG",
:pin "123123"}
```
response:
```clojure
{"whisper-address" "ec83f7354ca112203d2ce3e0b77b47e6e33258aa",
"whisper-private-key" "123123123123123123123123",
"wallet-root-public-key" "0424a93fe62a271ad230eb2957bf221b4644670589f5c0d69bd11f3371034674bf7875495816095006c2c0d5f834d628b87691a8bbe3bcc2225269020febd65a19",
"encryption-public-key" "0437eef85e669f800570f444e64baa2d0580e61cf60c0e9236b4108455ec1943f385043f759fcb5bd8348e32d6d6550a844cf24e57f68e9397a0f7c824a8caee2d",
"wallet-root-address" "6ff915f9f31f365511b1b8c1e40ce7f266caa5ce",
"whisper-public-key" "04b195df4336c596cca1b89555dc55dd6bb4c5c4491f352f6fdfae140a2349213423042023410f73a862aa188f6faa05c80b0344a1e39c253756cb30d8753f9f8324",
"address" "73509a1bb5f3b74d0dba143705cd9b4b55b8bba1",
"wallet-address" "2f0cc0e0859e7a05f319d902624649c7e0f48955",
"key-uid" "a5424fb033f5cc66dce9cbbe464426b6feff70ca40aa952c56247aaeaf4764a9",
"wallet-public-key" "04d6fab73772933215872c239787b2281f3b10907d099d04b88c861e713bd2b95883e0b1710a266830da29e76bbf6b87ed034ab139e36cc235a1b2a5b5ddfd4e91",
"public-key" "0437eef85e669f800570f444e64baa2d0580e61cf60c0e9236b4108455ec1943f385043f759fcb5bd8348e32d6d6550a844cf24e57f68e9397a0f7c824a8caee2d",
"instance-uid" "2268254e3ed7898839abe0b40e1b4200"}
```
3. `status-im.hardwallet.card/get-application-info`
params:
```clojure
{:pairing "ACEWbvUlordYWOE6M1Narn/AXICRltjyuKIAn4kkPXQG"}
```
response:
```clojure
{"paired?" true,
"has-master-key?" true,
"app-version" "2.2",
"free-pairing-slots" 4,
"pin-retry-counter" 3,
"puk-retry-counter" 5,
"initialized?" true,
"secure-channel-pub-key" "04b079ac513d5e0ebbe9becbae1618503419f5cb59edddc7d7bb09ce0db069a8e6dec1fb40c6b8e5454f7e1fcd0bb4a0b9750256afb4e4390e169109f3ea3ba91d",
"key-uid" "a5424fb033f5cc66dce9cbbe464426b6feff70ca40aa952c56247aaeaf4764a9",
"instance-uid" "2268254e3ed7898839abe0b40e1b4200"}
```
## Transaction signing
1. `status-im.hardwallet.card/get-application-info`
params:
```clojure
{:pairing "ALecvegKyOW4szknl01yYWx60GLDK5gDhxMgJECRZ+7h",
:on-success :hardwallet/sign}
```
response:
```clojure
{"paired?" true,
"has-master-key?" true,
"app-version" "2.2",
"free-pairing-slots" 4,
"pin-retry-counter" 3,
"puk-retry-counter" 5,
"initialized?" true,
"secure-channel-pub-key" "0476d11f2ccdad4e7779b95a1ce063d7280cb6c09afe2c0e48ca0c64ab9cf2b3c901d12029d6c266bfbe227c73a802561302b2330ac07a3270fc638ad258fced4a",
"key-uid" "d5c8cde8085e7a3fcf95aafbcbd7b3cfe32f61b85c2a8f662f60e76bdc100718",
"instance-uid" "e20e27bfee115b431e6e81b8e9dcf04c"}
```
2. `status-im.hardwallet.card/sign`
params:
```clojure
{:hash "92fc7ef54c3e0c42de256b93fbf2c49dc6948ee089406e204dec943b7a0142a9",
:pairing "ALecvegKyOW4szknl01yYWx60GLDK5gDhxMgJECRZ+7h",
:pin "123123",
:path "m/44'/60'/0'/0/0"}
```
response: `5d2ca075593cf50aa34007a0a1df7df14a369534450fce4a2ae8d023a9d9c0e216b5e5e3f64f81bee91613318d01601573fdb15c11887a3b8371e3291e894de600`
## Account derivation
1. `status-im.hardwallet.card/verify-pin`
params:
```clojure
{:pin "123123",
:pairing "ALecvegKyOW4szknl01yYWx60GLDK5gDhxMgJECRZ+7h"}
```
response: `3`
1. `status-im.hardwallet.card/export-key`
params:
```clojure
{:pin "123123",
:pairing "ALecvegKyOW4szknl01yYWx60GLDK5gDhxMgJECRZ+7h",
:path "m/44'/60'/0'/0/1"}
```
response: `046d1bcd2310a5e0094bc515b0ec995a8cb59e23d564094443af10011b6c00bdde44d160cdd32b4b6341ddd7dc83a4f31fdf60ec2276455649ccd7a22fa4ea01d8` (account's `public-key`)
## Reset pin
1. `status-im.hardwallet.card/change-pin`
params:
```clojure
{:new-pin "111111",
:current-pin "222222",
:pairing "AA0sKxPkN+jMHXZZeI8Rgz04AaY5Fg0CzVbm9189Khob"}
```
response:
`true`
## Unblock pin
If user enters a wrong pin three times in a row a card gets blocked. The user can use puk code then to unblock the card and set a new pin.
1. `status-im.hardwallet.card/unblock-pin`
params:
```clojure
{:puk "120702722103",
:new-pin "111111",
:pairing "AIoQl0OtCL0/uSN7Ct1/FHRMEk/eM2Lrhn0bw7f8sgOe"}
```
response
`true`
## Status go calls
In order to use the card in the app we need to use some parts of status-go API, specifically:
1. [`SaveAccountAndLoginWithKeycard`](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go#L337) after multiaccount creation/restoring to store multiaccount and login into it
2. [`LoginWithKeycard`](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go#L373) to log into already existing account
3. [`HashTransaction`](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go#L492) and [`HashMessage`](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go#L520) for hashing transaction/message before signing
4. [`SendTransactionWithSignature`](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go#L471) to send transaction
## Where are the keys stored?
1. When we create a regular multiaccount all its keys are stored on device and are encrypted via key which is derived from user's password. In case if account was created using keycard all keys are stored on the card and are retrieved from it during signing into multiaccount.
2. When we create a regular multiaccount we also create a separate database for it and this database is encrypted using key which is derived from user's password. For a keycard account we use `encryption-public-key` (returned by `status-im.hardwallet.card/get-keys`/`status-im.hardwallet.card/generate-and-load-keys`) as a password.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [Keycard Hardwallet Documentation](https://keycard.tech/docs/)
- [Keycard Codebase](https://github.com/status-im/status-go/blob/b33ad8147d23a932064f241e575511d70a601dcc/mobile/status.go)

View File

@@ -0,0 +1,52 @@
---
title: NOTIFICATIONS
name: Notifications
status: deprecated
description: A client should implement local notifications to offer notifications for any event in the app without the privacy cost and dependency on third party services.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Eric Dvorsak <eric@status.im>
---
## Local Notifications
A client should implement local notifications to offer notifications
for any event in the app without the privacy cost and dependency on third party services.
This means that the client should run a background service to continuously or periodically check for updates.
### Android
Android allows running services on the device. When the user enables notifications,
the client may start a ``Foreground Service`,
and display a permanent notification indicating that the service is running,
as required by Android guidelines.
The service will simply keep the app from being killed by the system when it is in the background.
The client will then be able to run in the background
and display local notifications on events such as receiving a message in a one to one chat.
To facilitate the implementation of local notifications,
a node implementation such as `status-go` may provide a specific `notification` signal.
Notifications are a separate process in Android, and interaction with a notification generates an `Intent`.
To handle intents, the `NewMessageSignalHandler` may use a `BroadcastReceiver`,
in order to update the state of local notifications when the user dismisses or tap a notification.
If the user taps on a notification, the `BroadcastReceiver` generates a new intent to open the app should use universal links to get the user to the right place.
### iOS
We are not able to offer local notifications on iOS because there is no concept of services in iOS.
It offers background updates but theyre not consistently triggered, and cannot be relied upon.
The system decides when the background updates are triggered and the heuristics aren't known.
## Why is there no Push Notifications?
Push Notifications, as offered by Apple and Google are a privacy concern,
they require a centralized service that is aware of who the notification needs to be delivered to.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- None

View File

@@ -0,0 +1,386 @@
---
title: PAYLOADS
name: Payloads
status: deprecated
description: Payload of messages in Status, regarding chat and chat-related use cases.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Andrea Maria Piana <andreap@status.im>
- Oskar Thorén <oskar@status.im>
---
## Abstract
This specification describes how the payload of each message in Status looks like.
It is primarily centered around chat and chat-related use cases.
The payloads aims to be flexible enough to support messaging but also cases
described in the [Status Whitepaper](https://status.im/whitepaper.pdf)
as well as various clients created using different technologies.
## Introduction
This document describes the payload format and some special considerations.
## Payload wrapper
The node wraps all payloads in a [protobuf record](https://developers.google.com/protocol-buffers/):
```protobuf
message ApplicationMetadataMessage {
bytes signature = 1;
bytes payload = 2;
Type type = 3;
enum Type {
UNKNOWN = 0;
CHAT_MESSAGE = 1;
CONTACT_UPDATE = 2;
MEMBERSHIP_UPDATE_MESSAGE = 3;
PAIR_INSTALLATION = 4;
SYNC_INSTALLATION = 5;
REQUEST_ADDRESS_FOR_TRANSACTION = 6;
ACCEPT_REQUEST_ADDRESS_FOR_TRANSACTION = 7;
DECLINE_REQUEST_ADDRESS_FOR_TRANSACTION = 8;
REQUEST_TRANSACTION = 9;
SEND_TRANSACTION = 10;
DECLINE_REQUEST_TRANSACTION = 11;
SYNC_INSTALLATION_CONTACT = 12;
SYNC_INSTALLATION_ACCOUNT = 13;
SYNC_INSTALLATION_PUBLIC_CHAT = 14;
CONTACT_CODE_ADVERTISEMENT = 15;
PUSH_NOTIFICATION_REGISTRATION = 16;
PUSH_NOTIFICATION_REGISTRATION_RESPONSE = 17;
PUSH_NOTIFICATION_QUERY = 18;
PUSH_NOTIFICATION_QUERY_RESPONSE = 19;
PUSH_NOTIFICATION_REQUEST = 20;
PUSH_NOTIFICATION_RESPONSE = 21;
}
}
```
`signature` is the bytes of the signed `SHA3-256` of the payload,
signed with the key of the author of the message.
The node needs the signature to validate authorship of the message,
so that the message can be relayed to third parties.
If a signature is not present, but an author is provided by a layer below,
the message is not to be relayed to third parties, and it is considered plausibly deniable.
`payload` is the protobuf encoded content of the message, with the corresponding `type` set.
## Encoding
The node encodes the payload using [Protobuf](https://developers.google.com/protocol-buffers)
## Types of messages
### Message
The type `ChatMessage` represents a chat message exchanged between clients.
#### Payload
The protobuf description is:
```protobuf
message ChatMessage {
// Lamport timestamp of the chat message
uint64 clock = 1;
// Unix timestamps in milliseconds, currently not used as we use Whisper/Waku as more reliable, but here
// so that we don't rely on it
uint64 timestamp = 2;
// Text of the message
string text = 3;
// Id of the message that we are replying to
string response_to = 4;
// Ens name of the sender
string ens_name = 5;
// Chat id, this field is symmetric for public-chats and private group chats,
// but asymmetric in case of one-to-ones, as the sender will use the chat-id
// of the received, while the receiver will use the chat-id of the sender.
// Probably should be the concatenation of sender-pk & receiver-pk in alphabetical order
string chat_id = 6;
// The type of message (public/one-to-one/private-group-chat)
MessageType message_type = 7;
// The type of the content of the message
ContentType content_type = 8;
oneof payload {
StickerMessage sticker = 9;
}
enum MessageType {
UNKNOWN_MESSAGE_TYPE = 0;
ONE_TO_ONE = 1;
PUBLIC_GROUP = 2;
PRIVATE_GROUP = 3;
// Only local
SYSTEM_MESSAGE_PRIVATE_GROUP = 4;}
enum ContentType {
UNKNOWN_CONTENT_TYPE = 0;
TEXT_PLAIN = 1;
STICKER = 2;
STATUS = 3;
EMOJI = 4;
TRANSACTION_COMMAND = 5;
// Only local
SYSTEM_MESSAGE_CONTENT_PRIVATE_GROUP = 6;
}
}
```
Payload
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | The clock of the chat|
| 2 | timestamp | `uint64` | The sender timestamp at message creation |
| 3 | text | `string` | The content of the message |
| 4 | response_to | `string` | The ID of the message replied to |
| 5 | ens_name | `string` | The ENS name of the user sending the message |
| 6 | chat_id | `string` | The local ID of the chat the message is sent to |
| 7 | message_type | `MessageType` | The type of message, different for one-to-one, public or group chats |
| 8 | content_type | `ContentType` | The type of the content of the message |
| 9 | payload | `Sticker\|nil` | The payload of the message based on the content type |
#### Content types
A node requires content types for a proper interpretation of incoming messages. Not each message is plain text but may carry different information.
The following content types MUST be supported:
* `TEXT_PLAIN` identifies a message which content is a plaintext.
There are other content types that MAY be implemented by the client:
* `STICKER`
* `STATUS`
* `EMOJI`
* `TRANSACTION_COMMAND`
##### Mentions
A mention MUST be represented as a string with the `@0xpk` format, where `pk` is the public key of the [user account](/status/deprecated/account.md) to be mentioned,
within the `text` field of a message with content_type `TEXT_PLAIN`.
A message MAY contain more than one mention.
This specification RECOMMENDs that the application does not require the user to enter the entire pk.
This specification RECOMMENDs that the application allows the user to create a mention
by typing @ followed by the related ENS or 3-word pseudonym.
This specification RECOMMENDs that the application provides the user auto-completion functionality to create a mention.
For better user experience, the client SHOULD display a known [ens name or the 3-word pseudonym corresponding to the key](/status/deprecated/account.md#contact-verification) instead of the `pk`.
##### Sticker content type
A `ChatMessage` with `STICKER` `Content/Type` MUST also specify the ID of the `Pack` and
the `Hash` of the pack, in the `Sticker` field of `ChatMessage`
```protobuf
message StickerMessage {
string hash = 1;
int32 pack = 2;
}
```
#### Message types
A node requires message types to decide how to encrypt a particular message
and what metadata needs to be attached when passing a message to the transport layer.
For more on this, see [WHISPER-USAGE](/status/deprecated/whisper-usage.md)
and [WAKU-USAGE](/status/deprecated/waku-usage.md).
<!-- TODO: This reference is a bit odd, considering the layer payloads should interact with is Secure Transport, and not Whisper/Waku. This requires more detail -->
The following messages types MUST be supported:
* `ONE_TO_ONE` is a message to the public group
* `PUBLIC_GROUP` is a private message
* `PRIVATE_GROUP` is a message to the private group.
#### Clock vs Timestamp and message ordering
If a user sends a new message before the messages sent
while the user was offline are received,
the newmessage is supposed to be displayed last in a chat.
This is where the basic algorithm of Lamport timestamp would fall short
as it's only meant to order causally related events.
The status client therefore makes a "bid", speculating that it will beat the current chat-timestamp, s.t. the status client's
Lamport timestamp format is: `clock = max({timestamp}, chat_clock + 1)`
This will satisfy the Lamport requirement, namely: a -> b then T(a) < T(b)
`timestamp` MUST be Unix time calculated, when the node creates the message, in milliseconds.
This field SHOULD not be relied upon for message ordering.
`clock` SHOULD be calculated using the algorithm of [Lamport timestamps](https://en.wikipedia.org/wiki/Lamport_timestamps).
When there are messages available in a chat,
the node calculates `clock`'s value based on the last received message in a particular chat: `max(timeNowInMs, last-message-clock-value + 1)`.
If there are no messages, `clock` is initialized with `timestamp`'s value.
Messages with a `clock` greater than `120` seconds over the Whisper/Waku timestamp SHOULD be discarded,
in order to avoid malicious users to increase the `clock` of a chat arbitrarily.
Messages with a `clock` less than `120` seconds under the Whisper/Waku timestamp
might indicate an attempt to insert messages in the chat history which is not distinguishable from a `datasync` layer re-transit event.
A client MAY mark this messages with a warning to the user, or discard them.
The node uses `clock` value for the message ordering.
The algorithm used, and the distributed nature of the system produces casual ordering, which might produce counter-intuitive results in some edge cases.
For example, when a user joins a public chat and sends a message
before receiving the exist messages, their message `clock` value might be lower
and the message will end up in the past when the historical messages are fetched.
#### Chats
Chat is a structure that helps organize messages.
It's usually desired to display messages only from a single recipient,
or a group of recipients at a time and chats help to achieve that.
All incoming messages can be matched against a chat.
The below table describes how to calculate a chat ID for each message type.
|Message Type|Chat ID Calculation|Direction|Comment|
|------------|-------------------|---------|-------|
|PUBLIC_GROUP|chat ID is equal to a public channel name; it should equal `chatId` from the message|Incoming/Outgoing||
|ONE_TO_ONE|let `P` be a public key of the recipient; `hex-encode(P)` is a chat ID; use it as `chatId` value in the message|Outgoing||
|user-message|let `P` be a public key of message's signature; `hex-encode(P)` is a chat ID; discard `chat-id` from message|Incoming|if there is no matched chat, it might be the first message from public key `P`; the node MAY discard the message or MAY create a new chat; Status official clients create a new chat|
|PRIVATE_GROUP|use `chatId` from the message|Incoming/Outgoing|find an existing chat by `chatId`; if none is found, the user is not a member of that chat or the user hasn't joined that chat, the message MUST be discarded |
### Contact Update
`ContactUpdate` is a message exchange to notify peers that either the
user has been added as a contact, or that information about the sending user have
changed.
```protobuf
message ContactUpdate {
uint64 clock = 1;
string ens_name = 2;
string profile_image = 3;
}
```
Payload
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | The clock of the chat with the user |
| 2 | ens_name | `string` | The ENS name if set |
| 3 | profile_image | `string` | The base64 encoded profile picture of the user |
#### Contact update
A client SHOULD send a `ContactUpdate` to all the contacts each time:
* The ens_name has changed
* A user edits the profile image
A client SHOULD also periodically send a `ContactUpdate` to all the contacts, the interval is up to the client,
the Status official client sends these updates every 48 hours.
### SyncInstallationContact
The node uses `SyncInstallationContact` messages to synchronize in a best-effort the contacts to other devices.
```protobuf
message SyncInstallationContact {
uint64 clock = 1;
string id = 2;
string profile_image = 3;
string ens_name = 4;
uint64 last_updated = 5;
repeated string system_tags = 6;
}
```
Payload
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | clock value of the chat |
| 2 | id | `string` | id of the contact synced |
| 3 | profile_image | `string` | `base64` encoded profile picture of the user |
| 4 | ens_name | `string` | ENS name of the contact |
| 5 | `array[string]` | Array of `system_tags` for the user, this can currently be: `":contact/added", ":contact/blocked", ":contact/request-received"`||
### SyncInstallationPublicChat
The node uses `SyncInstallationPublicChat` message to synchronize in a best-effort the public chats to other devices.
```protobuf
message SyncInstallationPublicChat {
uint64 clock = 1;
string id = 2;
}
```
Payload
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | clock value of the chat |
| 2 | id | `string` | id of the chat synced |
### PairInstallation
The node uses `PairInstallation` messages to propagate information about a device to its paired devices.
```protobuf
message PairInstallation {
uint64 clock = 1;
string installation_id = 2;
string device_type = 3;
string name = 4;
}
```
Payload
| Field | Name | Type | Description |
| ----- | ---- | ---- | ---- |
| 1 | clock | `uint64` | clock value of the chat |
| 2| installation_id | `string` | A randomly generated id that identifies this device |
| 3 | device_type | `string` | The OS of the device `ios`,`android` or `desktop` |
| 4 | name | `string` | The self-assigned name of the device |
### MembershipUpdateMessage and MembershipUpdateEvent
`MembershipUpdateEvent` is a message used to propagate information about group membership changes in a group chat.
The details are in the [Group chats specs](/status/deprecated/group-chat.md).
## Upgradability
There are two ways to upgrade the protocol without breaking compatibility:
* A node always supports accretion
* A node does not support deletion of existing fields or messages, which might break compatibility
## Security Considerations
## Changelog
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
* Added language to include Waku in all relevant places
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
[Status Whitepaper](https://status.im/whitepaper.pdf)
[protobuf record](https://developers.google.com/protocol-buffers/)
[Protobuf](https://developers.google.com/protocol-buffers)
[Status user account](/status/deprecated/account.md)
[ens name or the 3-word pseudonym corresponding to the key](deprecated/account/#contact-verification)
[WHISPER-USAGE](/status/deprecated/whisper-usage.md)
[WAKU-USAGE](/status/deprecated/waku-usage.md)
[Lamport timestamps](https://en.wikipedia.org/wiki/Lamport_timestamps)
[Group chats specs](/status/deprecated/group-chat.md)
[May 22, 2020 change commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)

View File

@@ -0,0 +1,753 @@
---
title: PUSH-NOTIFICATION-SERVER
name: Push notification server
status: deprecated
description: Status provides a set of Push notification services that can be used to achieve this functionality.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Andrea Maria Piana <andreap@status.im>
---
## Reason
Push notifications for iOS devices and some Android devices can only be implemented by relying on [APN service](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1) for iOS or [Firebase](https://firebase.google.com/).
This is useful for Android devices that do not support foreground services
or that often kill the foreground service.
iOS only allows certain kind of applications to keep a connection open when in the
background, VoIP for example, which current status client does not qualify for.
Applications on iOS can also request execution time when they are in the [background](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/updating_your_app_with_background_app_refresh)
but it has a limited set of use cases, for example it won't schedule any time
if the application was force quit,
and generally is not responsive enough to implement a push notification system.
Therefore Status provides a set of Push notification services
that can be used to achieve this functionality.
Because this can't be safely implemented in a privacy preserving manner,
clients MUST be given an option to opt-in to receiving and sending push notifications.
They are disabled by default.
## Requirements
The party releasing the app MUST possess a certificate for the Apple Push Notification service
and its has to run a [gorush](https://github.com/appleboy/gorush) publicly accessible server for sending the actual notification.
The party releasing the app, Status in this case, needs to run its own [gorush](https://github.com/appleboy/gorush)
## Components
### Gorush instance
A [gorush](https://github.com/appleboy/gorush) instance MUST be publicly available,
this will be used only by push notification servers.
### Push notification server
A push notification server used by clients to register for receiving and sending push notifications.
### Registering client
A Status client that wants to receive push notifications
### Sending client
A Status client that wants to send push notifications
## Registering with the push notification service
A client MAY register with one or more Push Notification services of their choice.
A `PNR message` (Push Notification Registration) MUST be sent to the [partitioned topic](status/deprecated/waku-usage/#partitioned-topic)
for the public key of the node, encrypted with this key.
The message MUST be wrapped in a [`ApplicationMetadataMessage`](status/deprecated/payload/#payload-wrapper) with type set to `PUSH_NOTIFICATION_REGISTRATION`.
The marshaled protobuf payload MUST also be encrypted with AES-GCM
using the DiffieHellman key generated from the client and server identity.
This is done in order to ensure that the extracted key from the signature will be
considered invalid if it can't decrypt the payload.
The content of the message MUST contain the following [protobuf record](https://developers.google.com/protocol-buffers/):
```protobuf
message PushNotificationRegistration {
enum TokenType {
UNKNOWN_TOKEN_TYPE = 0;
APN_TOKEN = 1;
FIREBASE_TOKEN = 2;
}
TokenType token_type = 1;
string device_token = 2;
string installation_id = 3;
string access_token = 4;
bool enabled = 5;
uint64 version = 6;
repeated bytes allowed_key_list = 7;
repeated bytes blocked_chat_list = 8;
bool unregister = 9;
bytes grant = 10;
bool allow_from_contacts_only = 11;
string apn_topic = 12;
bool block_mentions = 13;
repeated bytes allowed_mentions_chat_list = 14;
}
```
A push notification server will handle the message according to the following rules:
- it MUST extract the public key of the sender from the signature and verify that
the payload can be decrypted successfully.
- it MUST verify that `token_type` is supported
- it MUST verify that `device_token` is non empty
- it MUST verify that `installation_id` is non empty
- it MUST verify that `version` is non-zero and greater than the currently stored version for the public key and installation id of the sender, if any
- it MUST verify that `grant` is non empty and according to the [specs](#server-grant)
- it MUST verify that `access_token` is a valid [`uuid`](https://tools.ietf.org/html/rfc4122)
- it MUST verify that `apn_topic` is set if `token_type` is `APN_TOKEN`
If the message can't be decrypted, the message MUST be discarded.
If `token_type` is not supported, a response MUST be sent with `error` set to
`UNSUPPORTED_TOKEN_TYPE`.
If `token`,`installation_id`,`device_tokens`,`version` are empty, a response MUST
be sent with `error` set to `MALFORMED_MESSAGE`.
If the `version` is equal or less than the currently stored version, a response MUST
be sent with `error` set to `VERSION_MISMATCH`.
If any other error occurs the `error` should be set to `INTERNAL_ERROR`.
If the response is successful `success` MUST be set to `true` otherwise a response MUST be sent with `success` set to `false`.
`request_id` should be set to the `SHAKE-256` of the encrypted payload.
The response MUST be sent on the [partitioned topic](status/deprecated/waku-usage.md#partitioned-topic) of the sender
and MUST not be encrypted using the [secure transport](status/deprecated/secure-transport) to facilitate the usage of ephemeral keys.
The payload of the response is:
```protobuf
message PushNotificationRegistrationResponse {
bool success = 1;
ErrorType error = 2;
bytes request_id = 3;
enum ErrorType {
UNKNOWN_ERROR_TYPE = 0;
MALFORMED_MESSAGE = 1;
VERSION_MISMATCH = 2;
UNSUPPORTED_TOKEN_TYPE = 3;
INTERNAL_ERROR = 4;
}
}
```
The message MUST be wrapped in a [`ApplicationMetadataMessage`](status/deprecated/payloads.md#payload-wrapper) with type set to `PUSH_NOTIFICATION_REGISTRATION_RESPONSE`.
A client SHOULD listen for a response sent on the [partitioned topic](status/deprecated/waku-usage/#partitioned-topic)
that the key used to register.
If `success` is `true` the client has registered successfully.
If `success` is `false`:
- If `MALFORMED_MESSAGE` is returned, the request SHOULD NOT be retried without ensuring that it is correctly formed.
- If `INTERNAL_ERROR` is returned, the request MAY be retried, but the client MUST backoff exponentially
A client MAY register with multiple Push Notification Servers in order to increase availability.
A client SHOULD make sure that all the notification services they registered with have the same information about their tokens.
If no response is returned the request SHOULD be considered failed and MAY be retried with the same server or a different one, but clients MUST exponentially backoff after each trial.
If the request is successful the token SHOULD be [advertised](#advertising-a-push-notification-server) as described below
### Query topic
On successful registration the server MUST be listening to the topic derived from:
```protobuf
0XHexEncode(Shake256(CompressedClientPublicKey))
```
Using the topic derivation algorithm described [here](status/deprecated/waku-usage/#public-chats)
and listen for client queries.
### Server grant
A push notification server needs to demonstrate to a client that it was authorized
by the client to send them push notifications. This is done by building
a grant which is specific to a given client-server pair.
The grant is built as follow:
```protobuf
Signature(Keccak256(CompressedPublicKeyOfClient . CompressedPublicKeyOfServer . AccessToken), PrivateKeyOfClient)
```
When receiving a grant the server MUST be validate that the signature matches the registering client.
## Re-registering with the push notification server
A client SHOULD re-register with the node if the APN or FIREBASE token changes.
When re-registering a client SHOULD ensure that it has the most up-to-date
`PushNotificationRegistration` and increment `version` if necessary.
Once re-registered, a client SHOULD advertise the changes.
## Changing options
This is handled in exactly the same way as re-registering above.
## Unregistering from push notifications
To unregister a client MUST send a `PushNotificationRegistration` request as described
above with `unregister` set to `true`, or removing
their device information.
The server MUST remove all data about this user if `unregistering` is `true`,
apart from the `hash` of the public key and the `version` of the last options,
in order to make sure that old messages are not processed.
A client MAY unregister from a server on explicit logout if multiple chat keys
are used on a single device.
## Advertising a push notification server
Each user registered with one or more push notification servers SHOULD
advertise periodically the push notification services that they have registered with for each device they own.
```protobuf
message PushNotificationQueryInfo {
string access_token = 1;
string installation_id = 2;
bytes public_key = 3;
repeated bytes allowed_user_list = 4;
bytes grant = 5;
uint64 version = 6;
bytes server_public_key = 7;
}
message ContactCodeAdvertisement {
repeated PushNotificationQueryInfo push_notification_info = 1;
}
```
The message MUST be wrapped in a [`ApplicationMetadataMessage`](status/deprecated/payloads/#payload-wrapper) with type set to `PUSH_NOTIFICATION_QUERY_INFO`.
If no filtering is done based on public keys,
the access token SHOULD be included in the advertisement.
Otherwise it SHOULD be left empty.
This SHOULD be advertised on the [contact code topic](/status/deprecated/waku-usage.md#contact-code-topic)
and SHOULD be coupled with normal contact-code advertisement.
Every time a user register or re-register with a push notification service, their
contact-code SHOULD be re-advertised.
Multiple servers MAY be advertised for the same `installation_id` for redundancy reasons.
## Discovering a push notification server
To discover a push notification service for a given user, their [contact code topic](status/deprecated/waku-usage/#contact-code-topic)
SHOULD be listened to.
A mailserver can be queried for the specific topic to retrieve the most up-to-date
contact code.
## Querying the push notification server
If a token is not present in the latest advertisement for a user, the server
SHOULD be queried directly.
To query a server a message:
```protobuf
message PushNotificationQuery {
repeated bytes public_keys = 1;
}
```
The message MUST be wrapped in a [`ApplicationMetadataMessage`](status/deprecated/payloads/#payload-wrapper) with type set to `PUSH_NOTIFICATION_QUERY`.
MUST be sent to the server on the topic derived from the hashed public key of the
key we are querying, as [described above](#query-topic).
An ephemeral key SHOULD be used and SHOULD NOT be encrypted using the [secure transport](status/deprecated/secure-transport.md).
If the server has information about the client a response MUST be sent:
```protobuf
message PushNotificationQueryInfo {
string access_token = 1;
string installation_id = 2;
bytes public_key = 3;
repeated bytes allowed_user_list = 4;
bytes grant = 5;
uint64 version = 6;
bytes server_public_key = 7;
}
message PushNotificationQueryResponse {
repeated PushNotificationQueryInfo info = 1;
bytes message_id = 2;
bool success = 3;
}
```
A `PushNotificationQueryResponse` message MUST be wrapped in a [`ApplicationMetadataMessage`](status/deprecated/payloads.md#payload-wrapper) with type set to `PUSH_NOTIFICATION_QUERY_RESPONSE`.
Otherwise a response MUST NOT be sent.
If `allowed_key_list` is not set `access_token` MUST be set and `allowed_key_list` MUST NOT
be set.
If `allowed_key_list` is set `allowed_key_list` MUST be set and `access_token` MUST NOT be set.
If `access_token` is returned, the `access_token` SHOULD be used to send push notifications.
If `allowed_key_list` are returned, the client SHOULD decrypt each
token by generating an `AES-GCM` symmetric key from the DiffieHellman between the
target client and itself
If AES decryption succeeds it will return a valid [`uuid`](https://tools.ietf.org/html/rfc4122) which is what is used for access_token.
The token SHOULD be used to send push notifications.
The response MUST be sent on the [partitioned topic](status/deprecated/waku-usage/#partitioned-topic) of the sender
and MUST not be encrypted using the [secure transport](status/deprecated/secure-transport.md) to facilitate
the usage of ephemeral keys.
On receiving a response a client MUST verify `grant` to ensure that the server
has been authorized to send push notification to a given client.
## Sending a push notification
When sending a push notification, only the `installation_id` for the devices targeted
by the message SHOULD be used.
If a message is for all the user devices, all the `installation_id` known to the client MAY be used.
The number of devices MAY be capped in order to reduce resource consumption.
At least 3 devices SHOULD be targeted, ordered by last activity.
For any device that a token is available, or that a token is successfully queried,
a push notification message SHOULD be sent to the corresponding push notification server.
```protobuf
message PushNotification {
string access_token = 1;
string chat_id = 2;
bytes public_key = 3;
string installation_id = 4;
bytes message = 5;
PushNotificationType type = 6;
enum PushNotificationType {
UNKNOWN_PUSH_NOTIFICATION_TYPE = 0;
MESSAGE = 1;
MENTION = 2;
}
bytes author = 7;
}
message PushNotificationRequest {
repeated PushNotification requests = 1;
bytes message_id = 2;
}
```
A `PushNotificationRequest` message MUST be wrapped in a [`ApplicationMetadataMessage`](/status/deprecated/payloads.md#payload-wrapper) with type set to `PUSH_NOTIFICATION_REQUEST`.
Where `message` is the encrypted payload of the message and `chat_id` is the
`SHAKE-256` of the `chat_id`.
`message_id` is the id of the message
`author` is the `SHAKE-256` of the public key of the sender.
If multiple server are available for a given push notification, only one notification
MUST be sent.
If no response is received
a client SHOULD wait at least 3 seconds, after which the request MAY be retried against a different server
This message SHOULD be sent using an ephemeral key.
On receiving the message, the push notification server MUST validate the access token.
If the access token is valid, a notification MUST be sent to the gorush instance with the
following data:
```protobuf
{
"notifications": [
{
"tokens": ["token_a", "token_b"],
"platform": 1,
"message": "You have a new message",
"data": {
"chat_id": chat_id,
"message": message,
"installation_ids": [installation_id_1, installation_id_2]
}
}
]
}
```
Where platform is `1` for IOS and `2` for Firebase, according to the [gorush documentation](https://github.com/appleboy/gorush)
A server MUST return a response message:
```protobuf
message PushNotificationReport {
bool success = 1;
ErrorType error = 2;
enum ErrorType {
UNKNOWN_ERROR_TYPE = 0;
WRONG_TOKEN = 1;
INTERNAL_ERROR = 2;
NOT_REGISTERED = 3;
}
bytes public_key = 3;
string installation_id = 4;
}
message PushNotificationResponse {
bytes message_id = 1;
repeated PushNotificationReport reports = 2;
}
```
A `PushNotificationResponse` message MUST be wrapped in a [`ApplicationMetadataMessage`](/status/deprecated/payloads.md#payload-wrapper) with type set to `PUSH_NOTIFICATION_RESPONSE`.
Where `message_id` is the `message_id` sent by the client.
The response MUST be sent on the [partitioned topic](/status/deprecated/waku-usage.md#partitioned-topic) of the sender
and MUST not be encrypted using the [secure transport](/status/deprecated/secure-transport.md) to facilitate
the usage of ephemeral keys.
If the request is accepted `success` MUST be set to `true`.
Otherwise `success` MUST be set to `false`.
If `error` is `BAD_TOKEN` the client MAY query again the server for the token and
retry the request.
If `error` is `INTERNAL_ERROR` the client MAY retry the request.
## Flow
### Registration process
- A client will generate a notification token through `APN` or `Firebase`.
- The client will [register](#registering-with-the-push-notification-service) with one or more push notification server of their choosing.
- The server should process the response and respond according to the success of the operation
- If the request is not successful it might be retried, and adjusted according to the response. A different server can be also used.
- Once the request is successful the client should [advertise](#advertising-a-push-notification-server) the new coordinates
### Sending a notification
- A client should prepare a message and extract the targeted installation-ids
- It should retrieve the most up to date information for a given user, either by
querying a push notification server, a mailserver if not listening already to the given topic, or checking
the database locally
- It should then [send](#sending-a-push-notification) a push notification according
to the rules described
- The server should then send a request to the gorush server including all the required
information
### Receiving a push notification
- On receiving the notification, a client can open the right account by checking the
`installation_id` included. The `chat_id` MAY be used to open the chat if present.
- `message` can be decrypted and presented to the user. Otherwise messages can be pulled from the mailserver if the `message_id` is no already present.
## Protobuf description
### PushNotificationRegistration
`token_type`: the type of token. Currently supported is `APN_TOKEN` for Apple Push
`device_token`: the actual push notification token sent by `Firebase` or `APN`
and `FIREBASE_TOKEN` for firebase.
`installation_id`: the [`installation_id`](/status/deprecated/account.md) of the device
`access_token`: the access token that will be given to clients to send push notifications
`enabled`: whether the device wants to be sent push notifications
`version`: a monotonically increasing number identifying the current `PushNotificationRegistration`. Any time anything is changed in the record it MUST be increased by the client, otherwise the request will not be accepted.
`allowed_key_list`: a list of `access_token` encrypted with the AES key generated
by DiffieHellman between the publisher and the allowed
contact.
`blocked_chat_list`: a list of `SHA2-256` hashes of chat ids.
Any chat id in this list will not trigger a notification.
`unregister`: whether the account should be unregistered
`grant`: the grant for this specific server
`allow_from_contacts_only`: whether the client only wants push notifications from contacts
`apn_topic`: the APN topic for the push notification
`block_mentions`: whether the client does not want to be notified on mentions
`allowed_mentions_chat_list`: a list of `SHA2-256` hashes of chat ids where we want to receive mentions
#### Data disclosed
- Type of device owned by a given user
- The `FIREBASE` or `APN` push notification token
- Hash of the chat_id a user is not interested in for notifications
- The times a push notification record has been modified by the user
- The number of contacts a client has, in case `allowed_key_list` is set
### PushNotificationRegistrationResponse
`success`: whether the registration was successful
`error`: the error type, if any
`request_id`: the `SHAKE-256` hash of the `signature` of the request
`preferences`: the server stored preferences in case of an error
### ContactCodeAdvertisement
`push_notification_info`: the information for each device advertised
Data disclosed
- The chat key of the sender
### PushNotificationQuery
`public_keys`: the `SHAKE-256` of the public keys the client is interested in
Data disclosed
- The hash of the public keys the client is interested in
### PushNotificationQueryInfo
`access_token`: the access token used to send a push notification
`installation_id`: the `installation_id` of the device associated with the `access_token`
`public_key`: the `SHAKE-256` of the public key associated with this `access_token` and `installation_id`
`allowed_key_list`: a list of encrypted access tokens to be returned
to the client in case there's any filtering on public keys in place.
`grant`: the grant used to register with this server.
`version`: the version of the registration on the server.
`server_public_key`: the compressed public key of the server.
### PushNotificationQueryResponse
`info`: a list of `PushNotificationQueryInfo`.
`message_id`: the message id of the `PushNotificationQueryInfo` the server is replying to.
`success`: whether the query was successful.
### PushNotification
`access_token`: the access token used to send a push notification.
`chat_id`: the `SHAKE-256` of the `chat_id`.
`public_key`: the `SHAKE-256` of the compressed public key of the receiving client.
`installation_id`: the installation id of the receiving client.
`message`: the encrypted message that is being notified on.
`type`: the type of the push notification, either `MESSAGE` or `MENTION`
`author`: the `SHAKE-256` of the public key of the sender
Data disclosed
- The `SHAKE-256` of the `chat_id` the notification is to be sent for
- The cypher text of the message
- The `SHAKE-256` of the public key of the sender
- The type of notification
### PushNotificationRequest
`requests`: a list of `PushNotification`
`message_id`: the [status message id](/status/deprecated/payloads.md)
Data disclosed
- The status message id for which the notification is for
### PushNotificationResponse
`message_id`: the `message_id` being notified on.
`reports`: a list of `PushNotificationReport`
### PushNotificationReport
`success`: whether the push notification was successful.
`error`: the type of the error in case of failure.
`public_key`: the public key of the user being notified.
`installation_id`: the installation id of the user being notified.
## Anonymous mode of operations
An anonymous mode of operations MAY be provided by the client, where the
responsibility of propagating information about the user is left to the client,
in order to preserve privacy.
A client in anonymous mode can register with the server using a key different
from their chat key.
This will hide their real chat key.
This public key is effectively a secret and SHOULD only be disclosed to clients that you the user wants to be notified by.
A client MAY advertise the access token on the contact-code topic of the key generated.
A client MAY share their public key through [contact updates](/status/deprecated/payloads.md#contact-update)
A client receiving a push notification public key SHOULD listen to the contact code
topic of the push notification public key for updates.
The method described above effectively does not share the identity of the sender
nor the receiver to the server, but MAY result in missing push notifications as
the propagation of the secret is left to the client.
This can be mitigated by [device syncing](/status/deprecated/payloads.md), but not completely
addressed.
## Security considerations
If no anonymous mode is used, when registering with a push notification service a client discloses:
- The chat key
- The devices that will receive notifications
A client MAY disclose:
- The hash of the chat_ids they want to filter out
When running in anonymous mode, the client's chat key is not disclosed.
When querying a push notification server a client will disclose:
- That it is interested in sending push notification to another client,
but the querying client's chat key is not disclosed
When sending a push notification a client discloses:
- The `SHAKE-256` of the chat id
[//]: This section can be removed, for now leaving it here in order to help with the
review process. Point can be integrated, suggestion welcome.
## FAQ
### Why having ACL done at the server side and not the client?
We looked into silent notification for
[IOS](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app) (android has no equivalent)
but can't be used as it's expected to receive maximum 2/3 per hour, so not our use case. There
are also issue when the user force quit the app.
### Why using an access token?
The access token is used to decouple the requesting information from the user from
actually sending the push notification.
Some ACL is necessary otherwise it would be too easy to spam users (it's still fairly
trivial, but with this method you could allow only contacts to send you push notifications).
Therefore your identity must be revealed to the server either when sending or querying.
By using an access token we increase deniability, as the server would know
who requested the token but not necessarily who sent a push notification.
Correlation between the two can be trivial in some cases.
This also allows a mode of use as we had before, where the server does not propagate
info at all, and it's left to the user to propagate the token, through contact requests
for example.
### Why advertise with the bundle?
Advertising with the bundle allows us to piggy-back on an already implemented behavior
and save some bandwidth in cases where is not filtering by public keys
### What's the bandwidth impact for this?
Generally speaking, for each 1-to-1 message and group chat message you will sending
1 and `number of participants` push notifications. This can be optimized if
multiple users are using the same push notification server. Queries have also
a bandwidth impact but they are made only when actually needed
### What's the information disclosed?
The data disclosed with each message sent by the client is above, but for a summary:
When you register with a push notification service you may disclose:
1) Your chat key
2) Which devices you have
3) The hash of the chat_ids you want to filter out
4) The hash of the public keys you are interested/not interested in
When you query a notification service you may disclose:
1) Your chat key
2) The fact that you are interested in sending push notification to a given user
Effectively this is fairly revealing if the user has a whitelist implemented.
Therefore sending notification should be optional.
### What prevents a user from generating a random key and getting an access token and spamming?
Nothing really, that's the same as the status app as a whole. the only mechanism that prevents
this is using a white-list as described above,
but that implies disclosing your true identity to the push notification server.
### Why not 0-knowledge proofs/quantum computing
We start simple, we can iterate
### How to handle backward/forward compatibility
Most of the request have a target, so protocol negotiation can happen. We cannot negotiated
the advertisement as that's effectively a broadcast, but those info should not change and we can
always accrete the message.
### Why ack_key?
That's necessary to avoid duplicated push notifications and allow for the retry
in case the notification is not successful.
Deduplication of the push notification is done on the client side, to reduce a bit
of centralization and also in order not to have to modify gorush.
### Can I run my own node?
Sure, the methods allow that
### Can I register with multiple nodes for redundancy
Yep
### What does my node disclose?
Your node will disclose the IP address is running from, as it makes an HTTP post to
gorush. A waku adapter could be used, but please not now.
### Does this have high-reliability requirements?
The gorush server yes, no way around it.
The rest, kind of, at least one node having your token needs to be up for you to receive notifications.
But you can register with multiple servers (desktop, status, etc) if that's a concern.
### Can someone else (i.e not status) run this?
Push notification servers can be run by anyone. Gorush can be run by anyone I take,
but we are in charge of the certificate, so they would not be able to notify status-clients.
## Changelog
### Version 0.1
[Released](https://github.com/status-im/specs/commit/)
- Initial version
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [APN Service](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1)
- [Background Execution on iOS](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/updating_your_app_with_background_app_refresh)
- [Firebase](https://firebase.google.com/)
- [Gorush](https://github.com/appleboy/gorush)
- [UUID Specification](https://tools.ietf.org/html/rfc4122)
- [Secure Transport](/status/deprecated/secure-transport.md)
- [Silent Notifications on iOS](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app)
- [Waku Usage](/status/deprecated/waku-usage.md)
- [ENS Contract](https://github.com/ensdomains/ens)
- [Payloads](/status/deprecated/payloads.md)

View File

@@ -0,0 +1,583 @@
---
title: SECURE-TRANSPORT
name: Secure Transport
status: deprecated
description: This document describes how Status provides a secure channel between two peers, providing confidentiality, integrity, authenticity, and forward secrecy.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Andrea Maria Piana <andreap@status.im>
- Corey Petty <corey@status.im>
- Dean Eigenmann <dean@status.im>
- Oskar Thorén <oskar@status.im>
- Pedro Pombeiro <pedro@status.im>
---
## Abstract
This document describes how Status provides a secure channel between two peers,
and thus provide confidentiality, integrity, authenticity and forward secrecy.
It is transport-agnostic and works over asynchronous networks.
It builds on the [X3DH](https://signal.org/docs/specifications/x3dh/) and [Double Ratchet](https://signal.org/docs/specifications/doubleratchet/) specifications, with some adaptations to operate in a decentralized environment.
## Introduction
This document describes how nodes establish a secure channel,
and how various conversational security properties are achieved.
### Definitions
- **Perfect Forward Secrecy** is a feature of specific key-agreement protocols
which provide assurances that session keys will not be compromised even if the private keys of the participants are compromised.
Specifically, past messages cannot be decrypted by a third-party who manages to get a hold of a private key.
- **Secret channel** describes a communication channel where Double Ratchet algorithm is in use.
### Design Requirements
- **Confidentiality**: The adversary should not be able to learn what data is being exchanged between two Status clients.
- **Authenticity**: The adversary should not be able to cause either endpoint of a Status 1:1 chat
to accept data from any third party as though it came from the other endpoint.
- **Forward Secrecy**: The adversary should not be able to learn
what data was exchanged between two Status clients if, at some later time,
the adversary compromises one or both of the endpoint devices.
- **Integrity**: The adversary should not be able to cause either endpoint of a Status 1:1 chat
to accept data that has been tampered with.
All of these properties are ensured by the use of [Signal's Double Ratchet](https://signal.org/docs/specifications/doubleratchet/)
### Conventions
Types used in this specification are defined using [Protobuf](https://developers.google.com/protocol-buffers/).
### Transport Layer
[Whisper](status/deprecated/whisper-usage) and [Waku](status/deprecated/waku-usage) serves as the transport layers for the Status chat protocol.
### User flow for 1-to-1 communications
#### Account generation
See [Account specification](status/deprecated/account)
#### Account recovery
If Alice later recovers her account, the Double Ratchet state information will not be available,
so she is no longer able to decrypt any messages received from existing contacts.
If an incoming message (on the same Whisper/Waku topic) fails to decrypt,
the node replies a message with the current bundle, so that the node notifies the other end of the new device.
Subsequent communications will use this new bundle.
## Messaging
All 1:1 and group chat messaging in Status is subject to end-to-end encryption
to provide users with a strong degree of privacy and security.
Public chat messages are publicly readable by anyone since there's no permission model
for who is participating in a public chat.
The rest of this document is purely about 1:1 and private group chat.
Private group chat largely reduces to 1:1 chat, since there's a secure channel between each pair-wise participant.
### End-to-end encryption
End-to-end encryption (E2EE) takes place between two clients.
The main cryptographic protocol is a [Status implementation](https://github.com/status-im/doubleratchet/) of the Double Ratchet protocol,
which is in turn derived from the [Off-the-Record protocol](https://otr.cypherpunks.ca/Protocol-v3-4.1.1.html), using a different ratchet.
The transport protocol subsequently encrypt the message payload - Whisper/Waku (see section [Transport Layer](#transport-layer)) -, using symmetric key encryption.
Furthermore, Status uses the concept of prekeys (through the use of [X3DH](https://signal.org/docs/specifications/x3dh/))
to allow the protocol to operate in an asynchronous environment.
It is not necessary for two parties to be online at the same time to initiate an encrypted conversation.
Status uses the following cryptographic primitives:
- Whisper/Waku
- AES-256-GCM
- ECIES
- ECDSA
- KECCAK-256
- X3DH
- Elliptic curve Diffie-Hellman key exchange (secp256k1)
- KECCAK-256
- ECDSA
- ECIES
- Double Ratchet
- HMAC-SHA-256 as MAC
- Elliptic curve Diffie-Hellman key exchange (Curve25519)
- AES-256-CTR with HMAC-SHA-256 and IV derived alongside an encryption key
The node achieves key derivation using HKDF.
### Prekeys
Every client initially generates some key material which is stored locally:
- Identity keypair based on secp256k1 - `IK`
- A signed prekey based on secp256k1 - `SPK`
- A prekey signature - `Sig(IK, Encode(SPK))`
More details can be found in the `X3DH Prekey bundle creation` section of [2/ACCOUNT](/status/deprecated/account.md#x3dh-prekey-bundles).
Prekey bundles can be extracted from any user's messages,
or found via searching for their specific topic, `{IK}-contact-code`.
TODO: See below on bundle retrieval, this seems like enhancement and parameter for recommendation
### Bundle retrieval
<!-- TODO: Potentially move this completely over to [Trust Establishment](./status-account-spec.md) -->
X3DH works by having client apps create and make available a bundle of prekeys (the X3DH bundle)
that can later be requested by other interlocutors when they wish to start a conversation with a given user.
In the X3DH specification, nodes typically use a shared server
to store bundles and allow other users to download them upon request.
Given Status' goal of decentralization,
Status chat clients cannot rely on the same type of infrastructure
and must achieve the same result using other means.
By growing order of convenience and security, the considered approaches are:
- contact codes;
- public and one-to-one chats;
- QR codes;
- ENS record;
- Decentralized permanent storage (e.g. Swarm, IPFS).
- Whisper/Waku
<!-- TODO: Comment, it isn't clear what we actually _do_. It seems as if this is exploring the problem space. From a protocol point of view, it might make sense to describe the interface, and then have a recommendation section later on that specifies what we do. See e.g. Signal's specs where they specify specifics later on. -->
Currently, only public and one-to-one message exchanges and Whisper/Waku is used to exchange bundles.
Since bundles stored in QR codes or ENS records cannot be updated to delete already used keys,
the approach taken is to rotate more frequently the bundle (once every 24 hours),
which will be propagated by the app through the channel available.
### 1:1 chat contact request
There are two phases in the initial negotiation of a 1:1 chat:
1. **Identity verification** (e.g., face-to-face contact exchange through QR code, Identicon matching).
A QR code serves two purposes simultaneously - identity verification and initial bundle retrieval;
1. **Asynchronous initial key exchange**, using X3DH.
For more information on account generation and trust establishment, see [2/ACCOUNT](/status/deprecated/account.md)
#### Initial key exchange flow (X3DH)
[Section 3 of the X3DH protocol](https://signal.org/docs/specifications/x3dh/#sending-the-initial-message) describes the initial key exchange flow, with some additional context:
- The users' identity keys `IK_A` and `IK_B` correspond to their respective Status chat public keys;
- Since it is not possible to guarantee that a prekey will be used only once in a decentralized world,
the one-time prekey `OPK_B` is not used in this scenario;
- Nodes do not send Bundles to a centralized server, but instead served in a decentralized way as described in [bundle retrieval](#bundle-retrieval).
Alice retrieves Bob's prekey bundle, however it is not specific to Alice. It contains:
([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L12))
``` protobuf
// X3DH prekey bundle
message Bundle {
bytes identity = 1;
map<string,SignedPreKey> signed_pre_keys = 2;
bytes signature = 4;
int64 timestamp = 5;
}
```golang
- `identity`: Identity key `IK_B`
- `signed_pre_keys`: Signed prekey `SPK_B` for each device, indexed by `installation-id`
- `signature`: Prekey signature <i>Sig(`IK_B`, Encode(`SPK_B`))</i>
- `timestamp`: When the bundle was created locally
([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L5))
``` protobuf
message SignedPreKey {
bytes signed_pre_key = 1;
uint32 version = 2;
}
```
The `signature` is generated by sorting `installation-id` in lexicographical order, and concatenating the `signed-pre-key` and `version`:
`installation-id-1signed-pre-key1version1installation-id2signed-pre-key2-version-2`
#### Double Ratchet
Having established the initial shared secret `SK` through X3DH, it can be used to seed a Double Ratchet exchange between Alice and Bob.
Please refer to the [Double Ratchet spec](https://signal.org/docs/specifications/doubleratchet/) for more details.
The initial message sent by Alice to Bob is sent as a top-level `ProtocolMessage` ([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L65))
containing a map of `DirectMessageProtocol` indexed by `installation-id` ([protobuf](https://github.com/status-im/status-go/blob/1ac9dd974415c3f6dee95145b6644aeadf02f02c/services/shhext/chat/encryption.proto#L56)):
``` protobuf
message ProtocolMessage {
string installation_id = 2;
repeated Bundle bundles = 3;
// One to one message, encrypted, indexed by installation_id
map<string,DirectMessageProtocol> direct_message = 101;
// Public chats, not encrypted
bytes public_message = 102;
}
```
- `bundles`: a sequence of bundles
- `installation_id`: the installation id of the sender
- `direct_message` is a map of `DirectMessageProtocol` indexed by `installation-id`
- `public_message`: unencrypted public chat message.
``` protobuf
message DirectMessageProtocol {
X3DHHeader X3DH_header = 1;
DRHeader DR_header = 2;
DHHeader DH_header = 101;
// Encrypted payload
bytes payload = 3;
}
```
```protobuf
- `X3DH_header`: the `X3DHHeader` field in `DirectMessageProtocol` contains:
([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L47))
``` protobuf
message X3DHHeader {
bytes key = 1;
bytes id = 4;
}
```
- `key`: Alice's ephemeral key `EK_A`;
- `id`: Identifier stating which of Bob's prekeys Alice used, in this case Bob's bundle signed prekey.
Alice's identity key `IK_A` is sent at the transport layer level (Whisper/Waku);
- `DR_header`: Double ratchet header ([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L31)). Used when Bob's public bundle is available:
``` protobuf
message DRHeader {
bytes key = 1;
uint32 n = 2;
uint32 pn = 3;
bytes id = 4;
}
```
- `key`: Alice's current ratchet public key (as mentioned in [DR spec section 2.2](https://signal.org/docs/specifications/doubleratchet/#symmetric-key-ratchet));
- `n`: number of the message in the sending chain;
- `pn`: length of the previous sending chain;
- `id`: Bob's bundle ID.
- `DH_header`: Diffie-Helman header (used when Bob's bundle is not available):
([protobuf](https://github.com/status-im/status-go/blob/a904d9325e76f18f54d59efc099b63293d3dcad3/services/shhext/chat/encryption.proto#L42))
``` protobuf
message DHHeader {
bytes key = 1;
}
```
- `key`: Alice's compressed ephemeral public key.
- `payload`:
- if a bundle is available, contains payload encrypted with the Double Ratchet algorithm;
- otherwise, payload encrypted with output key of DH exchange (no Perfect Forward Secrecy).
```
<!-- TODO: A lot of links to status-go, seems likely these should be updated to status-protocol-go -->
## Security Considerations
The same considerations apply as in [section 4 of the X3DH spec](https://signal.org/docs/specifications/x3dh/#security-considerations) and [section 6 of the Double Ratchet spec](https://signal.org/docs/specifications/doubleratchet/#security-considerations), with some additions detailed below.
<!-- TODO: Add any additional context here not covered in the X3DH and DR specs -->
<!--
TODO: description here
### --- Security and Privacy Features
#### Confidentiality (YES)
> Only the intended recipients are able to read a message. Specifically, the message must not be readable by a server operator that is not a conversation participant
- Yes.
- There's a layer of encryption at Whisper as well as above with Double Ratchet
- Relay nodes and Mailservers can only read a topic of a Whisper message, and nothing within the payload.
#### Integrity (YES)
> No honest party will accept a message that has been modified in transit.
- Yes.
- Assuming a user validates (TODO: Check this assumption) every message they are able to decrypt and validate its signature from the sender, then it is not able to be altered in transit.
* [igorm] i'm really not sure about it, Whisper provides a signature, but I'm not sure we check it anywhere (simple grepping didn't give anything)
* [andrea] Whisper checks the signature and a public key is derived from it, we check the public key is a meaningful public key. The pk itself is not in the content of the message for public chats/1-to-1 so potentially you could send a message from a random account without having access to the private key, but that would not be much of a deal, as you might just as easily create a random account)
#### Authentication (YES)
> Each participant in the conversation receives proof of possession of a known long-term secret from all other participants that they believe to be participating in the conversation. In addition, each participant is able to verify that a message was sent from the claimed source
- 1:1 --- one-to-one messages are encrypted with the recipient's public key, and digitally signed by the sender's. In order to provide Perfect Forward Secrecy, we build on the X3DH and Double Ratchet specifications from Open Whisper Systems, with some adaptations to operate in a decentralized environment.
- group --- group chat is pairwise
- public --- A user subscribes to a public channel topic and the decryption key is derived from the topic name
**TODO:** Need to verify that this is actually the case
**TODO:** Fill in explicit details here
#### Participant Consistency (YES?)
> At any point when a message is accepted by an honest party, all honest parties are guaranteed to have the same view of the participant list
- **TODO:** Need details here
#### Destination Validation (YES?)
> When a message is accepted by an honest party, they can verify that they were included in the set of intended recipients for the message.
- Users are aware of the topic that a message was sent to, and that they have the ability to decrypt it.
-
#### Forward Secrecy (PARTIAL)
> Compromising all key material does not enable decryption of previously encrypted data
- After first back and forth between two contacts with PFS enabled, yes.
#### Backward Secrecy (YES)
> Compromising all key material does not enable decryption of succeeding encrypted data
- PFS requires both backward and forwards secrecy
[Andrea: This is not true, (Perfect) Forward Secrecy does not imply backward secrecy (which is also called post-compromise security, as signal calls it, or future secrecy, it's not well defined). Technically this is a NO , double ratchet offers good Backward secrecy, but not perfect. Effectively if all the key material is compromised, any future message received will be also compromised (due to the hash ratchet), until a DH ratchet step is completed (i.e. the compromised party generate a new random key and ratchet)]
#### Anonymity Preserving (PARTIAL)
> Any anonymity features provided by the underlying transport privacy architecture are not undermined (e.g., if the transport privacy system provides anonymity, the conversation security level does not de-anonymize users by linking key identifiers).
- by default, yes
- ENS Naming system attaches an identifier to a given public key
#### Speaker Consistency (PARTIAL)
> All participants agree on the sequence of messages sent by each participant. A protocol might perform consistency checks on blocks of messages during the protocol, or after every message is sent.
- We use Lamport timestamps for ordering of events.
- In addition to this, we use local timestamps to attempt a more intuitive ordering. [Andrea: currently this was introduced as a regression during performance optimization and might result in out-of-order messages if sent across day boundaries, so I consider it a bug and not part of the specs (it does not make the order more intuitive, quite the opposite as it might result in causally related messages being out-of-order, but helps dividing the messages in days)]
- Fundamentally, there's no single source of truth, nor consensus process for global ordering [Andrea: Global ordering does not need a consensus process i.e. if you order messages alphabetically, and you break ties consistently, you have global ordering, as all the participants will see the same ordering (as opposed to say order by the time the message was received locally), of course is not useful, you want to have causal + global to be meaningful]
TODO: Understand how this is different from Global Transcript
[Andrea: This is basically Global transcript for a single participants, we offer global transcript]
#### Causality Preserving (PARTIAL)
> Implementations can avoid displaying a message before messages that causally precede it
- Not yet, but in pipeline (data sync layer)
[Andrea: Messages are already causally ordered, we don't display messages that are causally related out-of-order, that's already granted by lamport timestamps]
TODO: Verify if this can be done already by looking at Lamport clock difference
#### Global Transcript (PARTIAL)
> All participants see all messages in the same order
- See directly above
[Andrea: messages are globally (total) ordered, so all participants see the same ordering]
#### Message Unlinkability (NO)
> If a judge is convinced that a participant authored one message in the conversation, this does not provide evidence that they authored other messages
- Currently, the Status software signs every messages sent with the user's public key, thus making it unable to provide unlinkability.
- This is not necessary though, and could be built in to have an option to not sign.
- Side note: moot account allows for this but is a function of the anonymity set that uses it. The more people that use this account the stronger the unlinkability.
#### Message Repudiation (NO)
> Given a conversation transcript and all cryptographic keys, there is no evidence that a given message was authored by any particular user
- All messages are digitally signed by their sender.
- The underlying transport, Whisper/Waku, does allow for unsigned messages, but we don't use it.
#### Participant Repudiation (NO)
> Given a conversation transcript and all cryptographic key material for all but one accused (honest) participant, there is no evidence that the honest participant was in a conversation with any of the other participants.
### --- Group related features
#### Computational Equality (YES)
> All chat participants share an equal computational load
- One a message is sent, all participants in a group chat perform the same steps to retrieve and decrypt it.
- If proof of work is actually used at the Whisper layer (basically turned off in Status) then the sender would have to do additional computational work to send messages.
#### Trust Equality (PARTIAL)
> No participant is more trusted or takes on more responsibility than any other
- 1:1 chats and public chats are equal
- group chats have admins (on purpose)
- Private Group chats have Administrators and Members. Upon construction, the creator is made an admin. These groups have the following privileges:
- Admins:
- Add group members
- Promote group members to admin
- Change group name
- Members:
- Accept invitation to group
- Leave group
- Non-Members:
- Invited by admins show up as "invited" in group; this leaks contact information
- Invited people don't opt-in to being invited
TODO: Group chat dynamics should have a documented state diagram
TODO: create issues for identity leak of invited members as well as current members of a group showing up who have not accepted yet [Andrea: that's an interesting point, didn't think of that. Currently we have this behavior for 2 reasons, backward compatibility with previous releases, which had no concept of joining, and also because we rely on other peers to propagate group info, so we don't have a single-message point of failure (the invitation), the first can be addressed easily, the second is trickier, without giving up the propagation mechanism (if we choose to give this up, then it's trivial)]
#### Subgroup Messaging (NO)
> Messages can be sent to a subset of participants without forming a new conversation
- This would require a new topic and either a new public chat or a new group chat
[Andrea: This is a YES, as messages are pairwise encrypted, and client-side fanout, so anyone could potentially send a message only to a subset of the group]
#### Contractible Membership (PARTIAL)
> After the conversation begins, participants can leave without restarting the protocol
- For 1:1, there is no way to ignore or block a user from sending you a message. This is currently in the pipeline.
- For public chats, Yes. A member simply stops subscribing to a specific topic and will no longer receive messages.
- For group chats: this assumes pairwise encryption OR key is renegotiated
- This only currently works on the identity level, and not the device level. A ghost device will have access to anything other devices have.
[Andrea: For group chats, that's possible as using pairwise encryption, also with group chats (which use device-to-device encryption), ghost devices is a bit more complicated, in general, they don't have access to the messages you send, i.e. If I send a message from device A1 to the group chat and there is a ghost device A2, it will not be able to decrypt the content, but will see that a message has been sent (as only paired devices are kept in sync, and those are explicitly approved by the user). Messages that you receive are different, so a ghost device (A2) will potentially be able to decrypt the message, but A1 can detect the ghost device (in most cases, it's complicated :), the pfs docs describe multi-device support), for one-to-one ghost devices are undetectable]
#### Expandable Membership (PARTIAL)
> After the conversation begins, participants can join without restarting the protocol.
- 1:1: no, only 1:1
- private group: yes, since it is pair-wise, each person in the group just creates a pair with the new member
- public: yes, as members of a public chat are only subscribing to a topic and receiving anyone sending messages to it.
### --- Usability and Adoption
#### Out-of-Order Resilient (PARTIAL)
> If a message is delayed in transit, but eventually arrives, its contents are accessible upon arrival
- Due to asynchronous forward secrecy and no additional services, private keys might be rotated
[Andrea: That's correct, in some cases if the message is delayed for too long, or really out-of-order, the specific message key might have been deleted, as we only keep the last 3000 message keys]
[Igor: TTL of a Whisper message can expire, so any node-in-transit will drop it. Also, I believe we ignore messages with skewed timestamps]
#### Dropped Message Resilient (PARTIAL)
> Messages can be decrypted without receipt of all previous messages. This is desirable for asynchronous and unreliable network services
- Public chats: yes, users are able to decrypt any message received at any time.
- 1-to-1/group chat also, this is a YES in my opinion
#### Asynchronous (PARTIAL)
> Messages can be sent securely to disconnected recipients and received upon their next connection
- The semantics around message reliability are currently poor
* [Igor: messages are stored on mailservers for way longer than TTL (30 days), but that requires Status infrastructure]
- There's a TTL in Whisper and mailserver can deliver messages after the fact
TODO: this requires more detail
#### Multi-Device Support (YES)
> A user can participate in the conversation using multiple devices at once. Each device must be able to send and receive messages. Ideally, all devices have identical views of the conversation. The devices might use a synchronized long-term key or distinct keys.
- Yes
- There is currently work being done to improve the syncing process between a user's devices.
#### No Additional Service (NO)
> The protocol does not require any infrastructure other than the protocol participants. Specifically, the protocol must not require additional servers for relaying messages or storing any kind of key material.
- The protocol requires Whisper/Waku relay servers and mailservers currently.
- The larger the number of Whisper/Waku relay servers, the better the transport security but there might be potential scaling problems.
- Mailservers act to provide asynchronicity so users can retrieve messages after coming back from an offline period.
-->
## Session management
A node identifies a peer by two pieces of data:
1) An `installation-id` which is generated upon creating a new account in the `Status` application
2) Their identity Whisper/Waku key
### Initialization
A node initializes a new session once a successful X3DH exchange has taken place. Subsequent messages will use the established session until re-keying is necessary.
### Concurrent sessions
If a node creates two sessions concurrently between two peers, the one with the symmetric key first in byte order SHOULD be used, this marks that the other has expired.
### Re-keying
On receiving a bundle from a given peer with a higher version, the old bundle SHOULD be marked as expired and a new session SHOULD be established on the next message sent.
### Multi-device support
Multi-device support is quite challenging as there is not a central place
where information on which and how many devices (identified by their respective `installation-id`) belongs to a whisper-identity / waku-identity.
Furthermore, account recovery always needs to be taken into consideration,
where a user wipes clean the whole device and the nodes loses all the information about any previous sessions.
Taking these considerations into account, the way the network propagates multi-device information using x3dh bundles,
which will contain information about paired devices as well as information about the sending device.
This means that every time a new device is paired, the bundle needs to be updated and propagated with the new information,
the user has the responsibility to make sure the pairing is successful.
The method is loosely based on [Sesame](https://signal.org/docs/specifications/sesame/).
### Pairing
When a user adds a new account in the `Status` application, a new `installation-id` will be generated.
The device should be paired as soon as possible if other devices are present.
Once paired the contacts will be notified of the new device and it will be included in further communications.
If a bundle received from the `IK` is different to the `installation-id`,
the device will be shown to the user and will have to be manually approved, to a maximum of 3.
Once that is done any message sent by one device will also be sent to any other enabled device.
Once a user enables a new device, a new bundle will be generated which will include pairing information.
The bundle will be propagated to contacts through the usual channels.
Removal of paired devices is a manual step that needs to be applied on each device,
and consist simply in disabling the device, at which point pairing information will not be propagated anymore.
### Sending messages to a paired group
When sending a message, the peer will send a message to other `installation-id` that they have seen.
The node caps the number of devices to 3, ordered by last activity.
The node sends messages using pairwise encryption, including their own devices.
Account recovery
Account recovery is no different from adding a new device, and it is handled in exactly the same way.
### Partitioned devices
In some cases (i.e. account recovery when no other pairing device is available, device not paired),
it is possible that a device will receive a message that is not targeted to its own `installation-id`.
In this case an empty message containing bundle information is sent back,
which will notify the receiving end of including this device in any further communication.
## Changelog
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
- Added language to include Waku in all relevant places
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [X3DH](https://signal.org/docs/specifications/x3dh/)
- [Double Ratchet](https://signal.org/docs/specifications/doubleratchet/)
- [Protobuf](https://developers.google.com/protocol-buffers/)
- [Whisper](/status/deprecated/whisper-usage.md)
- [Waku](/status/deprecated/waku-usage.md)
- [Account specification](/status/deprecated/account.md)
- [Status implementation](https://github.com/status-im/doubleratchet/)
- [Off-the-Record protocol](https://otr.cypherpunks.ca/Protocol-v3-4.1.1.html)
- [X3DH](https://signal.org/docs/specifications/x3dh/)
- [ACCOUNT](/status/deprecated/account.md)
- [Sesame](https://signal.org/docs/specifications/sesame/)
- [May 22, 2020 commit change](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)

View File

@@ -0,0 +1,138 @@
---
title: WAKU-MAILSERVER
name: Waku Mailserver
status: deprecated
description: Waku Mailserver is a specification that allows messages to be stored permanently and to allow the stored messages to be delivered to requesting client nodes, regardless if the messages are not available in the network due to the message TTL expiring.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Oskar Thorén <oskar@status.im>
- Samuel Hawksby-Robinson <samuel@status.im>
---
## Abstract
Being mostly offline is an intrinsic property of mobile clients.
They need to save network transfer and battery consumption to avoid spending too much money or constant charging.
Waku protocol, on the other hand, is an online protocol.
Messages are available in the Waku network only for short period of time calculate in seconds.
Waku Mailserver is a specification that allows messages to be stored permanently
and allows the stored messages to be delivered to requesting client nodes,
regardless if the messages are not available in the network due to the message TTL expiring.
## `Mailserver`
From the network perspective, a `Mailserver` is just like any other Waku node.
The only difference is that a `Mailserver` has the capability of archiving messages
and delivering them to its peers on-demand.
It is important to notice that a `Mailserver` will only handle requests from its direct peers
and exchanged packets between a `Mailserver` and a peer are p2p messages.
### Archiving messages
A node which wants to provide `Mailserver` functionality MUST store envelopes from
incoming message packets (Waku packet-code `0x01`). The envelopes can be stored in any
format, however they MUST be serialized and deserialized to the Waku envelope format.
A `Mailserver` SHOULD store envelopes for all topics to be generally useful for any peer,
however for specific use cases it MAY store envelopes for a subset of topics.
### Requesting messages
In order to request historic messages, a node MUST send a packet P2P Request (`0x7e`) to a peer providing `Mailserver` functionality.
This packet requires one argument which MUST be a Waku envelope.
In the Waku envelope's payload section, there MUST be RLP-encoded information about the details of the request:
```golang
[ Lower, Upper, Bloom, Limit, Cursor ]
```
`Lower`: 4-byte wide unsigned integer (UNIX time in seconds; oldest requested envelope's creation time)
`Upper`: 4-byte wide unsigned integer (UNIX time in seconds; newest requested envelope's creation time)
`Bloom`: 64-byte wide array of Waku topics encoded in a bloom filter to filter envelopes
`Limit`: 4-byte wide unsigned integer limiting the number of returned envelopes
`Cursor`: an array of a cursor returned from the previous request (optional)
The `Cursor` field SHOULD be filled in if a number of envelopes between `Lower` and `Upper` is greater than `Limit`
so that the requester can send another request using the obtained `Cursor` value.
What exactly is in the `Cursor` is up to the implementation.
The requester SHOULD NOT use a `Cursor` obtained from one `Mailserver` in a request to another `Mailserver` because the format or the result MAY be different.
The envelope MUST be encrypted with a symmetric key agreed between the requester and the `Mailserver`.
### Receiving historic messages
Historic messages MUST be sent to a peer as a packet with a P2P Message code (`0x7f`) followed by an array of Waku envelopes.
In order to receive historic messages from a `Mailserver`, a node MUST trust the selected `Mailserver`,
that is allowed to send packets with the P2P Message code. By default, the node discards such packets.
Received envelopes MUST be passed through the Waku envelope pipelines
so that they are picked up by registered filters and passed to subscribers.
For a requester, to know that all messages have been sent by a `Mailserver`,
it SHOULD handle P2P Request Complete code (`0x7d`). This code is followed by the following parameters:
```golang
[ RequestID, LastEnvelopeHash, Cursor ]
```
* `RequestID`: 32-byte wide array with a Keccak-256 hash of the envelope containing the original request
* `LastEnvelopeHash`: 32-byte wide array with a Keccak-256 hash of the last sent envelope for the request
* `Cursor`: an array of a cursor returned from the previous request (optional)
If `Cursor` is not empty, it means that not all messages were sent due to the set `Limit` in the request.
One or more consecutive requests MAY be sent with `Cursor` field filled in order to receive the rest of the messages.
## Security considerations
### Confidentiality
The node encrypts all Waku envelopes. A `Mailserver` node can not inspect their contents.
### Altruistic and centralized operator risk
In order to be useful, a `Mailserver` SHOULD be online most of time.
That means users either have to be a bit tech-savvy to run their own node,
or rely on someone else to run it for them.
Currently, one of Status's legal entities provides `Mailservers` in an altruistic manner,
but this is suboptimal from a decentralization, continuance and risk point of view.
Coming up with a better system for this is ongoing research.
A Status client SHOULD allow the `Mailserver` selection to be customizable.
### Privacy concerns
In order to use a `Mailserver`, a given node needs to connect to it directly,
i.e. add the `Mailserver` as its peer and mark it as trusted.
This means that the `Mailserver` is able to send direct p2p messages to the node instead of broadcasting them.
Effectively, it will have access to the bloom filter of topics that the user is interested in,
when it is online as well as many metadata like IP address.
### Denial-of-service
Since a `Mailserver` is delivering expired envelopes and has a direct TCP connection with the recipient,
the recipient is vulnerable to DoS attacks from a malicious `Mailserver` node.
## Changelog
### Version 0.1
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
* Created document
* Forked from [whisper-mailserver](/status/deprecated/whisper-mailserver.md)
* Change to keep `Mailserver` term consistent
* Replaced Whisper references with Waku
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
* [May 22, 2020 change commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)

View File

@@ -0,0 +1,392 @@
---
title: WAKU-USAGE
name: Waku Usage
status: deprecated
description: Status uses Waku to provide privacy-preserving routing and messaging on top of devP2P.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Corey Petty <corey@status.im>
- Oskar Thorén <oskar@status.im>
- Samuel Hawksby-Robinson <samuel@status.im>
---
## Abstract
Status uses [Waku](/waku/standards/legacy/6/waku1.md) to provide privacy-preserving routing
and messaging on top of devP2P.
Waku uses topics to partition its messages,
and these are leveraged for all chat capabilities.
In the case of public chats, the channel name maps directly to its Waku topic.
This allows anyone to listen on a single channel.
Additionally, since anyone can receive Waku envelopes,
it relies on the ability to decrypt messages to decide who is the correct recipient.
Status nodes do not rely upon this property,
and implement another secure transport layer on top of Whisper.
## Reason
Provide routing, metadata protection, topic-based multicasting and basic
encryption properties to support asynchronous chat.
## Terminology
* *Waku node*: an Ethereum node with Waku V1 enabled
* *Waku network*: a group of Waku nodes connected together through the internet connection and forming a graph
* *Message*: a decrypted Waku message
* *Offline message*: an archived envelope
* *Envelope*: an encrypted message with metadata like topic and Time-To-Live
## Waku packets
| Packet Name | Code | References |
| -------------------- | ---: | --- |
| Status | 0 | [Status](status), [WAKU-1](/waku/standards/legacy/6/waku1.md#status) |
| Messages | 1 | [WAKU-1](/waku/standards/legacy/6/waku1.md#messages) |
| Batch Ack | 11 | Undocumented. Marked for Deprecation |
| Message Response | 12 | [WAKU-1](/waku/standards/legacy/6/waku1.md#batch-ack-and-message-response) |
| Status Update | 22 | [WAKU-1](/waku/standards/legacy/6/waku1.md#status-update) |
| P2P Request Complete | 125 | [4/WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md) |
| P2P Request | 126 | [4/WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md), [WAKU-1](/waku/standards/legacy/6/waku1.md#p2p-request) |
| P2P Messages | 127 | [4/WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md), [WAKU-1](/waku/standards/legacy/6/waku1.md#p2p-request-complete) |
## Waku node configuration
A Waku node must be properly configured to receive messages from Status clients.
Nodes use Waku's Proof Of Work algorithm to deter denial of service and various spam/flood attacks against the Whisper network.
The sender of a message must perform some work which in this case means processing time.
Because Status' main client is a mobile client, this easily leads to battery draining and poor performance of the app itself.
Hence, all clients MUST use the following Whisper node settings:
* proof-of-work requirement not larger than `0.002` for payloads less than 50,000 bytes
* proof-of-work requirement not larger than `0.000002` for payloads greater than or equal to 50,000 bytes
* time-to-live not lower than `10` (in seconds)
## Status
Handshake is a RLP-encoded packet sent to a newly connected peer. It MUST start with a Status Code (`0x00`) and follow up with items:
```golang
[
[ pow-requirement-key pow-requirement ]
[ bloom-filter-key bloom-filter ]
[ light-node-key light-node ]
[ confirmations-enabled-key confirmations-enabled ]
[ rate-limits-key rate-limits ]
[ topic-interest-key topic-interest ]
]
```
| Option Name | Key | Type | Description | References |
| ----------------------- | ------ | -------- | ----------- | --- |
| `pow-requirement` | `0x00` | `uint64` | minimum PoW accepted by the peer | [WAKU-1#pow-requirement](/waku/standards/legacy/6/waku1.md#pow-requirement-field) |
| `bloom-filter` | `0x01` | `[]byte` | bloom filter of Waku topic accepted by the peer | [WAKU-1#bloom-filter](/waku/standards/legacy/6/waku1.md#bloom-filter-field) |
| `light-node` | `0x02` | `bool` | when true, the peer won't forward envelopes through the Messages packet. | [WAKU-1#light-node](/waku/standards/legacy/6/waku1.md#light-node) |
| `confirmations-enabled` | `0x03` | `bool` | when true, the peer will send message confirmations | [WAKU-1#confirmations-enabled-field](/waku/standards/legacy/6/waku1.md#confirmations-enabled-field) |
| `rate-limits` | `0x04` | | See [Rate limiting](/waku/standards/legacy/6/waku1.md#rate-limits-field) | [WAKU-1#rate-limits](/waku/standards/legacy/6/waku1.md#rate-limits-field) |
| `topic-interest` | `0x05` | `[10000][4]byte` | Topic interest is used to share a node's interest in envelopes with specific topics. It does this in a more bandwidth considerate way, at the expense of some metadata protection. Peers MUST only send envelopes with specified topics. | [WAKU-1#topic-interest](/waku/standards/legacy/6/waku1.md#topic-interest-field), [the theoretical scaling model](https://github.com/vacp2p/research/tree/dcc71f4779be832d3b5ece9c4e11f1f7ec24aac2/whisper_scalability) |
<!-- TODO Add `light-node` and `confirmations-enabled` links when https://github.com/vacp2p/specs/pull/128 is merged -->
## Rate limiting
In order to provide an optional very basic Denial-of-Service attack protection, each node SHOULD define its own rate limits.
The rate limits SHOULD be applied on IPs, peer IDs, and envelope topics.
Each node MAY decide to whitelist, i.e. do not rate limit, selected IPs or peer IDs.
If a peer exceeds node's rate limits, the connection between them MAY be dropped.
Each node SHOULD broadcast its rate limits to its peers using `rate limits` in `status-options` via packet code `0x00` or `0x22`. The rate limits is RLP-encoded information:
```golang
[ IP limits, PeerID limits, Topic limits ]
```
`IP limits`: 4-byte wide unsigned integer
`PeerID limits`: 4-byte wide unsigned integer
`Topic limits`: 4-byte wide unsigned integer
The rate limits MAY also be sent as an optional parameter in the handshake.
Each node SHOULD respect rate limits advertised by its peers. The number of packets SHOULD be throttled in order not to exceed peer's rate limits.
If the limit gets exceeded, the connection MAY be dropped by the peer.
## Keys management
The protocol requires a key (symmetric or asymmetric) for the following actions:
* signing & verifying messages (asymmetric key)
* encrypting & decrypting messages (asymmetric or symmetric key).
As nodes require asymmetric keys and symmetric keys to process incoming messages,
they must be available all the time and are stored in memory.
Keys management for PFS is described in [5/SECURE-TRANSPORT](/status/deprecated/secure-transport.md).
The Status protocols uses a few particular Waku topics to achieve its goals.
### Contact code topic
Nodes use the contact code topic to facilitate the discovery of X3DH bundles so that the first message can be PFS-encrypted.
Each user publishes periodically to this topic. If user A wants to contact user B, she SHOULD look for their bundle on this contact code topic.
Contact code topic MUST be created following the algorithm below:
```golang
contactCode := "0x" + hexEncode(activePublicKey) + "-contact-code"
var hash []byte = keccak256(contactCode)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
### Partitioned topic
Waku is broadcast-based protocol. In theory, everyone could communicate using a single topic but that would be extremely inefficient.
Opposite would be using a unique topic for each conversation, however,
this brings privacy concerns because it would be much easier to detect whether and when two parties have an active conversation.
Nodes use partitioned topics to broadcast private messages efficiently.
By selecting a number of topic, it is possible to balance efficiency and privacy.
Currently, nodes set the number of partitioned topics to `5000`. They MUST be generated following the algorithm below:
```golang
var partitionsNum *big.Int = big.NewInt(5000)
var partition *big.Int = big.NewInt(0).Mod(publicKey.X, partitionsNum)
partitionTopic := "contact-discovery-" + strconv.FormatInt(partition.Int64(), 10)
var hash []byte = keccak256(partitionTopic)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
### Public chats
A public chat MUST use a topic derived from a public chat name following the algorithm below:
```golang
var hash []byte
hash = keccak256(name)
topicLen = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
<!-- NOTE: commented out as it is currently not used. In code for potential future use. - C.P. Oct 8, 2019
### Personal discovery topic
Personal discovery topic is used to ???
A client MUST implement it following the algorithm below:
```golang
personalDiscoveryTopic := "contact-discovery-" + hexEncode(publicKey)
var hash []byte = keccak256(personalDiscoveryTopic)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
Each Status Client SHOULD listen to this topic in order to receive ??? -->
### Group chat topic
Group chats does not have a dedicated topic.
All group chat messages (including membership updates) are sent as one-to-one messages to multiple recipients.
### Negotiated topic
When a client sends a one to one message to another client, it MUST listen to their negotiated topic.
This is computed by generating a diffie-hellman key exchange between two members
and taking the first four bytes of the `SHA3-256` of the key generated.
```golang
sharedKey, err := ecies.ImportECDSA(myPrivateKey).GenerateShared(
ecies.ImportECDSAPublic(theirPublicKey),
16,
16,
)
hexEncodedKey := hex.EncodeToString(sharedKey)
var hash []byte = keccak256(hexEncodedKey)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
A client SHOULD send to the negotiated topic only if it has received a message from all the devices included in the conversation.
### Flow
To exchange messages with client `B`, a client `A` SHOULD:
* Listen to client's `B` Contact Code Topic to retrieve their bundle information, including a list of active devices
* Send a message on client's `B` partitioned topic
* Listen to the Negotiated Topic between `A` & `B`
* Once client `A` receives a message from `B`, the Negotiated Topic SHOULD be used
## Message encryption
Even though, the protocol specifies an encryption layer that encrypts messages before passing them to the transport layer,
Waku protocol requires each Waku message to be encrypted anyway.
The node encrypts public and group messages using symmetric encryption, and creates the key from a channel name string.
The implementation is available in [`shh_generateSymKeyFromPassword`](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_generatesymkeyfrompassword) JSON-RPC method of go-ethereum Whisper implementation.
The node encrypts one-to-one messages using asymmetric encryption.
## Message confirmations
Sending a message is a complex process where many things can go wrong.
Message confirmations tell a node that a message originating from it has been seen by its direct peers.
A node MAY send a message confirmation for any batch of messages received in a packet Messages Code (`0x01`).
A node sends a message confirmation using Batch Acknowledge packet (`0x0b`) or Message Response packet (`0x0c`).
The Batch Acknowledge packet is followed by a keccak256 hash of the envelopes batch data (raw bytes).
The Message Response packet is more complex and is followed by a Versioned Message Response:
```golang
[ Version, Response]
```
`Version`: a version of the Message Response, equal to `1`,
`Response`: `[ Hash, Errors ]` where `Hash` is a keccak256 hash of the envelopes batch data (raw bytes)
for which the confirmation is sent and `Errors` is a list of envelope errors when processing the batch.
A single error contains `[ Hash, Code, Description ]` where `Hash` is a hash of the processed envelope,
`Code` is an error code and `Description` is a descriptive error message.
The supported codes:
`1`: means time sync error which happens when an envelope is too old
or created in the future (the root cause is no time sync between nodes).
The drawback of sending message confirmations is that it increases the noise in the network because for each sent message,
one or more peers broadcast a corresponding confirmation. To limit that, both Batch Acknowledge packet (`0x0b`)
and Message Response packet (`0x0c`) are not broadcast to peers of the peers, i.e. they do not follow epidemic spread.
In the current Status network setup, only `Mailservers` support message confirmations.
A client posting a message to the network and after receiving a confirmation can be sure that the message got processed by the `Mailserver`.
If additionally, sending a message is limited to non-`Mailserver` peers,
it also guarantees that the message got broadcast through the network and it reached the selected `Mailserver`.
## Waku V1 extensions
### Request historic messages
Sends a request for historic messages to a `Mailserver`.
The `Mailserver` node MUST be a direct peer and MUST be marked as trusted (using `waku_markTrustedPeer`).
The request does not wait for the response.
It merely sends a peer-to-peer message to the `Mailserver` and it's up to `Mailserver` to process it and start sending historic messages.
The drawback of this approach is that it is impossible to tell which historic messages are the result of which request.
It's recommended to return messages from newest to oldest.
To move further back in time, use `cursor` and `limit`.
#### wakuext_requestMessages
**Parameters**:
* Object - The message request object:
* `mailServerPeer` - `String`: `Mailserver`'s enode address.
* `from` - `Number` (optional): Lower bound of time range as unix timestamp, default is 24 hours back from now.
* `to` - `Number` (optional): Upper bound of time range as unix timestamp, default is now.
* `limit` - `Number` (optional): Limit the number of messages sent back, default is no limit.
* `cursor` - `String` (optional): Used for paginated requests.
* `topics` - `Array`: hex-encoded message topics.
* `symKeyID` - `String`: an ID of a symmetric key used to authenticate with the `Mailserver`, derived from the `Mailserver` password.
**Returns**:
`Boolean` - returns `true` if the request was sent.
The above `topics` is then converted into a bloom filter and then and sent to the `Mailserver`.
<!-- TODO: Clarify actual request with bloom filter to mailserver -->
## Changelog
### Version 0.1
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
* Created document
* Forked from [3-whisper-usage](3-whisper-usage.md)
* Change to keep `Mailserver` term consistent
* Replaced Whisper references with Waku
* Added [Status options](#status) section
* Updated [Waku packets](#waku-packets) section to match Waku
* Added that `Batch Ack` is marked for deprecation
* Changed `shh_generateSymKeyFromPassword` to `waku_generateSymKeyFromPassword`
* [Exists here](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/waku/api.go#L172-L175)
* [Exists here](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/eth-node/bridge/geth/public_waku_api.go#L33-L36)
* Changed `shh_markTrustedPeer` to `waku_markTrustedPeer`
* [Exists here](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/waku/api.go#L100-L108)
* Changed `shhext_requestMessages` to `wakuext_requestMessages`
* [Exists here](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/services/wakuext/api.go#L76-L139)
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
* [Waku](waku)
* [WAKU1](/waku/standards/legacy/6/waku1.md)
* [WAKU-MAILSERVER](/status/deprecated/waku-mailserver.md)
* [The theoretical scaling model](https://github.com/vacp2p/research/tree/dcc71f4779be832d3b5ece9c4e11f1f7ec24aac2/whisper_scalability)
* [SECURE-TRANSPORT](/status/deprecated/secure-transport.md)
* [May 22, 2020 commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
* [`shh_generateSymKeyFromPassword`](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_generatesymkeyfrompassword)
* [Key Change #1](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/waku/api.go#L172-L175)
* [Key Change #2](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/eth-node/bridge/geth/public_waku_api.go#L33-L36)
* [Key Change #3](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/waku/api.go#L100-L108)
* [Key Change #4](https://github.com/status-im/status-go/blob/2d13ccf5ec3db7e48d7a96a7954be57edb96f12f/services/wakuext/api.go#L76-L139)

View File

@@ -0,0 +1,148 @@
---
title: WHISPER-MAILSERVER
name: Whisper mailserver
status: deprecated
description: Whisper Mailserver is a Whisper extension that allows to store messages permanently and deliver them to the clients even though they are already not available in the network and expired.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Oskar Thorén <oskar@status.im>
---
## Abstract
Being mostly offline is an intrinsic property of mobile clients.
They need to save network transfer and battery consumption
to avoid spending too much money or constant charging.
Whisper protocol, on the other hand, is an online protocol.
Messages are available in the Whisper network only for short period of time calculate in seconds.
Whisper `Mailserver` is a Whisper extension that allows to store messages permanently
and deliver them to the clients even though they are already not available in the network and expired.
## `Mailserver`
From the network perspective, `Mailserver` is just like any other Whisper node.
The only difference is that it has a capability of archiving messages and delivering them to its peers on-demand.
It is important to notice that `Mailserver` will only handle requests from its direct peers
and exchanged packets between `Mailserver` and a peer are p2p messages.
### Archiving messages
A node which wants to provide `Mailserver` functionality MUST store envelopes
from incoming message packets (Whisper packet-code `0x01`).
The envelopes can be stored in any format,
however they MUST be serialized and deserialized to the Whisper envelope format.
A `Mailserver` SHOULD store envelopes for all topics to be generally useful for any peer,
however for specific use cases it MAY store envelopes for a subset of topics.
### Requesting messages
In order to request historic messages, a node MUST send a packet P2P Request (`0x7e`) to a peer providing `Mailserver` functionality.
This packet requires one argument which MUST be a Whisper envelope.
In the Whisper envelope's payload section, there MUST be RLP-encoded information about the details of the request:
```golang
[ Lower, Upper, Bloom, Limit, Cursor ]
```
`Lower`: 4-byte wide unsigned integer (UNIX time in seconds; oldest requested envelope's creation time)
`Upper`: 4-byte wide unsigned integer (UNIX time in seconds; newest requested envelope's creation time)
`Bloom`: 64-byte wide array of Whisper topics encoded in a bloom filter to filter envelopes
`Limit`: 4-byte wide unsigned integer limiting the number of returned envelopes
`Cursor`: an array of a cursor returned from the previous request (optional)
The `Cursor` field SHOULD be filled in
if a number of envelopes between `Lower` and `Upper` is greater than `Limit`
so that the requester can send another request using the obtained `Cursor` value.
What exactly is in the `Cursor` is up to the implementation.
The requester SHOULD NOT use a `Cursor` obtained from one `Mailserver` in a request to another `Mailserver`
because the format or the result MAY be different.
The envelope MUST be encrypted with a symmetric key agreed between the requester and `Mailserver`.
### Receiving historic messages
Historic messages MUST be sent to a peer as a packet with a P2P Message code (`0x7f`)
followed by an array of Whisper envelopes.
It is incompatible with the original Whisper spec (EIP-627) because it allows only a single envelope,
however, an array of envelopes is much more performant.
In order to stay compatible with EIP-627, a peer receiving historic message MUST handle both cases.
In order to receive historic messages from a `Mailserver`, a node MUST trust the selected `Mailserver`,
that is allowed to send packets with the P2P Message code. By default, the node discards such packets.
Received envelopes MUST be passed through the Whisper envelope pipelines
so that they are picked up by registered filters and passed to subscribers.
For a requester, to know that all messages have been sent by `Mailserver`,
it SHOULD handle P2P Request Complete code (`0x7d`). This code is followed by the following parameters:
```golang
[ RequestID, LastEnvelopeHash, Cursor ]
```
`RequestID`: 32-byte wide array with a Keccak-256 hash of the envelope containing the original request
`LastEnvelopeHash`: 32-byte wide array with a Keccak-256 hash of the last sent envelope for the request
`Cursor`: an array of a cursor returned from the previous request (optional)
If `Cursor` is not empty, it means that not all messages were sent due to the set `Limit` in the request.
One or more consecutive requests MAY be sent with `Cursor` field filled in order to receive the rest of the messages.
## Security considerations
### Confidentiality
The node encrypts all Whisper envelopes. A `Mailserver` node can not inspect their contents.
### Altruistic and centralized operator risk
In order to be useful, a `Mailserver` SHOULD be online most of the time. That means
users either have to be a bit tech-savvy to run their own node, or rely on someone
else to run it for them.
Currently, one of Status's legal entities provides `Mailservers` in an altruistic manner, but this is
suboptimal from a decentralization, continuance and risk point of view. Coming
up with a better system for this is ongoing research.
A Status client SHOULD allow the `Mailserver` selection to be customizable.
### Privacy concerns
In order to use a `Mailserver`, a given node needs to connect to it directly,
i.e. add the `Mailserver` as its peer and mark it as trusted.
This means that the `Mailserver` is able to send direct p2p messages to the node instead of broadcasting them.
Effectively, it will have access to the bloom filter of topics
that the user is interested in,
when it is online as well as many metadata like IP address.
### Denial-of-service
Since a `Mailserver` is delivering expired envelopes and has a direct TCP connection with the recipient,
the recipient is vulnerable to DoS attacks from a malicious `Mailserver` node.
## Changelog
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
- Change to keep `Mailserver` term consistent
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
- [Whisper](https://eips.ethereum.org/EIPS/eip-627)
- [EIP-627](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-627.md)
- [SECURE-TRANSPORT](/status/deprecated/secure-transport.md)
- [`shh_generateSymKeyFromPassword`](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_generatesymkeyfrompassword)
- [Whisper v6](https://eips.ethereum.org/EIPS/eip-627)
- [Waku V0](/waku/deprecated/5/waku0.md)
- [Waku V1](/waku/standards/legacy/6/waku1.md)
- [May 22, 2020 change commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)

View File

@@ -0,0 +1,401 @@
---
title: WHISPER-USAGE
name: Whisper Usage
status: deprecated
description: Status uses Whisper to provide privacy-preserving routing and messaging on top of devP2P.
editor: Filip Dimitrijevic <filip@status.im>
contributors:
- Adam Babik <adam@status.im>
- Andrea Piana <andreap@status.im>
- Corey Petty <corey@status.im>
- Oskar Thorén <oskar@status.im>
---
## Abstract
Status uses [Whisper](https://eips.ethereum.org/EIPS/eip-627) to provide
privacy-preserving routing and messaging on top of devP2P.
Whisper uses topics to partition its messages,
and these are leveraged for all chat capabilities.
In the case of public chats, the channel name maps directly to its Whisper topic.
This allows anyone to listen on a single channel.
Additionally, since anyone can receive Whisper envelopes,
it relies on the ability to decrypt messages to decide who is the correct recipient.
Status nodes do not rely upon this property,
and implement another secure transport layer on top of Whisper.
Finally, using an extension of Whisper provides the ability to do offline messaging.
## Reason
Provide routing, metadata protection, topic-based multicasting and basic
encryption properties to support asynchronous chat.
## Terminology
* *Whisper node*: an Ethereum node with Whisper V6 enabled (in the case of go-ethereum, it's `--shh` option)
* *Whisper network*: a group of Whisper nodes connected together through the internet connection and forming a graph
* *Message*: a decrypted Whisper message
* *Offline message*: an archived envelope
* *Envelope*: an encrypted message with metadata like topic and Time-To-Live
## Whisper packets
| Packet Name | Code | EIP-627 | References |
| --- | --: | --- | --- |
| Status | 0 | ✔ | [Handshake](#handshake) |
| Messages | 1 | ✔ | [EIP-627](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-627.md) |
| PoW Requirement | 2 | ✔ | [EIP-627](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-627.md) |
| Bloom Filter | 3 | ✔ | [EIP-627](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-627.md) |
| Batch Ack | 11 | 𝘅 | Undocumented |
| Message Response | 12 | 𝘅 | Undocumented |
| P2P Sync Request | 123 | 𝘅 | Undocumented |
| P2P Sync Response | 124 | 𝘅 | Undocumented |
| P2P Request Complete | 125 | 𝘅 | [4/WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md) |
| P2P Request | 126 | ✔ | [4/WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md) |
| P2P Messages | 127 | ✔/𝘅 (EIP-627 supports only single envelope in a packet) | [4/WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md) |
## Whisper node configuration
A Whisper node must be properly configured to receive messages from Status clients.
Nodes use Whisper's Proof Of Work algorithm to deter denial of service
and various spam/flood attacks against the Whisper network.
The sender of a message must perform some work which in this case means processing time.
Because Status' main client is a mobile client, this easily leads to battery draining and poor performance of the app itself.
Hence, all clients MUST use the following Whisper node settings:
* proof-of-work requirement not larger than `0.002`
* time-to-live not lower than `10` (in seconds)
## Handshake
Handshake is a RLP-encoded packet sent to a newly connected peer. It MUST start with a Status Code (`0x00`) and follow up with items:
```golang
[ protocolVersion, PoW, bloom, isLightNode, confirmationsEnabled, rateLimits ]
```
`protocolVersion`: version of the Whisper protocol
`PoW`: minimum PoW accepted by the peer
`bloom`: bloom filter of Whisper topic accepted by the peer
`isLightNode`: when true, the peer won't forward messages
`confirmationsEnabled`: when true, the peer will send message confirmations
`rateLimits`: is `[ RateLimitIP, RateLimitPeerID, RateLimitTopic ]` where each values is an integer with a number of accepted packets per second per IP, Peer ID, and Topic respectively
`bloom, isLightNode, confirmationsEnabled, and rateLimits` are all optional arguments in the handshake. However, if an optional field is specified, all optional fields preceding it MUST also be specified in order to be unambiguous.
## Rate limiting
In order to provide an optional very basic Denial-of-Service attack protection, each node SHOULD define its own rate limits.
The rate limits SHOULD be applied on IPs, peer IDs, and envelope topics.
Each node MAY decide to whitelist, i.e. do not rate limit, selected IPs or peer IDs.
If a peer exceeds node's rate limits, the connection between them MAY be dropped.
Each node SHOULD broadcast its rate limits to its peers using rate limits packet code (`0x14`). The rate limits is RLP-encoded information:
```golang
[ IP limits, PeerID limits, Topic limits ]
```
`IP limits`: 4-byte wide unsigned integer
`PeerID limits`: 4-byte wide unsigned integer
`Topic limits`: 4-byte wide unsigned integer
The rate limits MAY also be sent as an optional parameter in the handshake.
Each node SHOULD respect rate limits advertised by its peers.
The number of packets SHOULD be throttled in order not to exceed peer's rate limits.
If the limit gets exceeded, the connection MAY be dropped by the peer.
## Keys management
The protocol requires a key (symmetric or asymmetric) for the following actions:
* signing & verifying messages (asymmetric key)
* encrypting & decrypting messages (asymmetric or symmetric key).
As nodes require asymmetric keys and symmetric keys to process incoming messages,
they must be available all the time and are stored in memory.
Keys management for PFS is described in [5/SECURE-TRANSPORT](/status/deprecated/whisper-mailserver.md).
The Status protocols uses a few particular Whisper topics to achieve its goals.
### Contact code topic
Nodes use the contact code topic to facilitate the discovery of X3DH bundles so that the first message can be PFS-encrypted.
Each user publishes periodically to this topic.
If user A wants to contact user B, she SHOULD look for their bundle on this contact code topic.
Contact code topic MUST be created following the algorithm below:
```golang
contactCode := "0x" + hexEncode(activePublicKey) + "-contact-code"
var hash []byte = keccak256(contactCode)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
### Partitioned topic
Whisper is broadcast-based protocol.
In theory, everyone could communicate using a single topic but that would be extremely inefficient.
Opposite would be using a unique topic for each conversation,
however, this brings privacy concerns because it would be much easier to detect whether
and when two parties have an active conversation.
Nodes use partitioned topics to broadcast private messages efficiently.
By selecting a number of topic, it is possible to balance efficiency and privacy.
Currently, nodes set the number of partitioned topics to `5000`.
They MUST be generated following the algorithm below:
```golang
var partitionsNum *big.Int = big.NewInt(5000)
var partition *big.Int = big.NewInt(0).Mod(publicKey.X, partitionsNum)
partitionTopic := "contact-discovery-" + strconv.FormatInt(partition.Int64(), 10)
var hash []byte = keccak256(partitionTopic)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
### Public chats
A public chat MUST use a topic derived from a public chat name following the algorithm below:
```golang
var hash []byte
hash = keccak256(name)
topicLen = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
<!-- NOTE: commented out as it is currently not used. In code for potential future use. - C.P. Oct 8, 2019
### Personal discovery topic
Personal discovery topic is used to ???
A client MUST implement it following the algorithm below:
```golang
personalDiscoveryTopic := "contact-discovery-" + hexEncode(publicKey)
var hash []byte = keccak256(personalDiscoveryTopic)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
Each Status Client SHOULD listen to this topic in order to receive ??? -->
<!-- NOTE: commented out as it is no longer valid as of V1. - C.P. Oct 8, 2019
### Generic discovery topic
Generic discovery topic is a legacy topic used to handle all one-to-one chats. The newer implementation should rely on [Partitioned Topic](#partitioned-topic) and [Personal discovery topic](#personal-discovery-topic).
Generic discovery topic MUST be created following [Public chats](#public-chats) topic algorithm using string `contact-discovery` as a name. -->
### Group chat topic
Group chats does not have a dedicated topic.
All group chat messages (including membership updates) are sent as one-to-one messages to multiple recipients.
### Negotiated topic
When a client sends a one to one message to another client, it MUST listen to their negotiated topic.
This is computed by generating a diffie-hellman key exchange between two members
and taking the first four bytes of the `SHA3-256` of the key generated.
```golang
sharedKey, err := ecies.ImportECDSA(myPrivateKey).GenerateShared(
ecies.ImportECDSAPublic(theirPublicKey),
16,
16,
)
hexEncodedKey := hex.EncodeToString(sharedKey)
var hash []byte = keccak256(hexEncodedKey)
var topicLen int = 4
if len(hash) < topicLen {
topicLen = len(hash)
}
var topic [4]byte
for i = 0; i < topicLen; i++ {
topic[i] = hash[i]
}
```
A client SHOULD send to the negotiated topic only if it has received a message from all the devices included in the conversation.
### Flow
To exchange messages with client `B`, a client `A` SHOULD:
* Listen to client's `B` Contact Code Topic to retrieve their bundle information, including a list of active devices
* Send a message on client's `B` partitioned topic
* Listen to the Negotiated Topic between `A` & `B`
* Once client `A` receives a message from `B`, the Negotiated Topic SHOULD be used
## Message encryption
Even though, the protocol specifies an encryption layer that encrypts messages before passing them to the transport layer,
Whisper protocol requires each Whisper message to be encrypted anyway.
The node encrypts public and group messages using symmetric encryption, and creates the key from a channel name string.
The implementation is available in [`shh_generateSymKeyFromPassword`](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_generatesymkeyfrompassword) JSON-RPC method of go-ethereum Whisper implementation.
The node encrypts one-to-one messages using asymmetric encryption.
## Message confirmations
Sending a message is a complex process where many things can go wrong.
Message confirmations tell a node that a message originating from it has been seen by its direct peers.
A node MAY send a message confirmation for any batch of messages received in a packet Messages Code (`0x01`).
A node sends a message confirmation using Batch Acknowledge packet (`0x0b`) or Message Response packet (`0x0c`).
The Batch Acknowledge packet is followed by a keccak256 hash of the envelopes batch data (raw bytes).
The Message Response packet is more complex and is followed by a Versioned Message Response:
```golang
[ Version, Response]
```
`Version`: a version of the Message Response, equal to `1`,
`Response`: `[ Hash, Errors ]` where `Hash` is a keccak256 hash of the envelopes batch data (raw bytes)
for which the confirmation is sent and `Errors` is a list of envelope errors when processing the batch.
A single error contains `[ Hash, Code, Description ]` where `Hash` is a hash of the processed envelope,
`Code` is an error code and `Description` is a descriptive error message.
The supported codes:
`1`: means time sync error which happens when an envelope is too old
or created in the future (the root cause is no time sync between nodes).
The drawback of sending message confirmations is that it increases the noise in the network because for each sent message,
one or more peers broadcast a corresponding confirmation.
To limit that, both Batch Acknowledge packet (`0x0b`) and Message Response packet (`0x0c`) are not broadcast to peers of the peers,
i.e. they do not follow epidemic spread.
In the current Status network setup, only `Mailservers` support message confirmations.
A client posting a message to the network and after receiving a confirmation can be sure that the message got processed by the `Mailserver`.
If additionally, sending a message is limited to non-`Mailserver` peers,
it also guarantees that the message got broadcast through the network and it reached the selected `Mailserver`.
## Whisper / Waku bridging
In order to maintain compatibility between Whisper and Waku nodes,
a Status network that implements both Whisper and Waku messaging protocols
MUST have at least one node that is capable of discovering peers and implements
[Whisper v6](https://eips.ethereum.org/EIPS/eip-627),
[Waku V0](/waku/deprecated/5/waku0.md) and
[Waku V1](/waku/standards/legacy/6/waku1.md) specifications.
Additionally, any Status network that implements both Whisper and Waku messaging protocols
MUST implement bridging capabilities as detailed in
[Waku V1#Bridging](/waku/standards/legacy/6/waku1.md#waku-whisper-bridging).
## Whisper V6 extensions
### Request historic messages
Sends a request for historic messages to a `Mailserver`.
The `Mailserver` node MUST be a direct peer and MUST be marked as trusted (using `shh_markTrustedPeer`).
The request does not wait for the response.
It merely sends a peer-to-peer message to the `Mailserver`
and it's up to `Mailserver` to process it and start sending historic messages.
The drawback of this approach is that it is impossible to tell
which historic messages are the result of which request.
It's recommended to return messages from newest to oldest.
To move further back in time, use `cursor` and `limit`.
#### shhext_requestMessages
**Parameters**:
1. Object - The message request object:
* `mailServerPeer` - `String`: `Mailserver`'s enode address.
* `from` - `Number` (optional): Lower bound of time range as unix timestamp, default is 24 hours back from now.
* `to` - `Number` (optional): Upper bound of time range as unix timestamp, default is now.
* `limit` - `Number` (optional): Limit the number of messages sent back, default is no limit.
* `cursor` - `String` (optional): Used for paginated requests.
* `topics` - `Array`: hex-encoded message topics.
* `symKeyID` - `String`: an ID of a symmetric key used to authenticate with the `Mailserver`, derived from Mailserver password.
**Returns**:
`Boolean` - returns `true` if the request was sent.
The above `topics` is then converted into a bloom filter and then and sent to the `Mailserver`.
<!-- TODO: Clarify actual request with bloom filter to mailserver -->
## Changelog
### Version 0.3
Released [May 22, 2020](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)
* Added Whisper / Waku Bridging section
* Change to keep `Mailserver` term consistent
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
## References
* [Whisper](https://eips.ethereum.org/EIPS/eip-627)
* [WHISPER-MAILSERVER](/status/deprecated/whisper-mailserver.md)
* [SECURE-TRANSPORT](/status/deprecated/secure-transport.md)
* [`shh_generateSymKeyFromPassword`](https://github.com/ethereum/go-ethereum/wiki/Whisper-v6-RPC-API#shh_generatesymkeyfrompassword)
* [Whisper v6](https://eips.ethereum.org/EIPS/eip-627)
* [Waku V0](/waku/deprecated/5/waku0.md)
* [Waku V1](/waku/standards/legacy/6/waku1.md)
* [May 22, 2020 change commit](https://github.com/status-im/specs/commit/664dd1c9df6ad409e4c007fefc8c8945b8d324e8)