github.com/core-coin/go-core/v2@v2.1.9/cmd/clef/tutorial.md (about)

     1  ## Initializing Clef
     2  
     3  First things first, Clef needs to store some data itself. Since that data might be sensitive (passwords, signing rules, accounts), Clef's entire storage is encrypted. To support encrypting data, the first step is to initialize Clef with a random master seed, itself too encrypted with your chosen password:
     4  
     5  ```text
     6  $ clef init
     7  
     8  WARNING!
     9  
    10  Clef is an account management tool. It may, like any software, contain bugs.
    11  
    12  Please take care to
    13  - backup your keystore files,
    14  - verify that the keystore(s) can be opened with your password.
    15  
    16  Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
    17  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
    18  PURPOSE. See the GNU General Public License for more details.
    19  
    20  Enter 'ok' to proceed:
    21  > ok
    22  
    23  The master seed of clef will be locked with a password.
    24  Please specify a password. Do not forget this password!
    25  Password:
    26  Repeat password:
    27  
    28  A master seed has been generated into /home/martin/.clef/masterseed.json
    29  
    30  This is required to be able to store credentials, such as:
    31  * Passwords for keystores (used by rule engine)
    32  * Storage for JavaScript auto-signing rules
    33  * Hash of JavaScript rule-file
    34  
    35  You should treat 'masterseed.json' with utmost secrecy and make a backup of it!
    36  * The password is necessary but not enough, you need to back up the master seed too!
    37  * The master seed does not contain your accounts, those need to be backed up separately!
    38  ```
    39  
    40  *For readability purposes, we'll remove the WARNING printout, user confirmation and the unlocking of the master seed in the rest of this document.*
    41  
    42  ## Remote interactions
    43  
    44  Clef is capable of managing both key-file based accounts as well as hardware wallets. To evaluate clef, we're going to point it to our testnet keystore and specify the Devin chain ID for signing (Clef doesn't have a backing chain, so it doesn't know what network it runs on).
    45  
    46  ```text
    47  $ clef --keystore ~/.core/devin/keystore --networkid 3
    48  
    49  INFO [07-01|11:00:46.385] Starting signer                          networkid=3 keystore=$HOME/.core/devin/keystore light-kdf=false advanced=false
    50  DEBUG[07-01|11:00:46.389] FS scan times                            list=3.521941ms set=9.017µs diff=4.112µs
    51  DEBUG[07-01|11:00:46.391] Ledger support enabled
    52  INFO [07-01|11:00:46.391] Audit logs configured                    file=audit.log
    53  DEBUG[07-01|11:00:46.392] IPC registered                           namespace=account
    54  INFO [07-01|11:00:46.392] IPC endpoint opened                      url=$HOME/.clef/clef.ipc
    55  ------- Signer info -------
    56  * intapi_version : 7.0.0
    57  * extapi_version : 6.0.0
    58  * extapi_http : n/a
    59  * extapi_ipc : $HOME/.clef/clef.ipc
    60  ```
    61  
    62  By default, Clef starts up in CLI (Command Line Interface) mode. Arbitrary remote processes may *request* account interactions (e.g. sign a transaction), which the user will need to individually *confirm*.
    63  
    64  To test this out, we can *request* Clef to list all account via its *External API endpoint*:
    65  
    66  ```text
    67  echo '{"id": 1, "jsonrpc": "2.0", "method": "account_list"}' | nc -U ~/.clef/clef.ipc
    68  ```
    69  
    70  This will prompt the user within the Clef CLI to confirm or deny the request:
    71  
    72  ```text
    73  -------- List Account request--------------
    74  A request has been made to list all accounts.
    75  You can select which accounts the caller can see
    76    [x] 0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3
    77      URL: keystore://$HOME/.core/devin/keystore/UTC--2017-04-14T15-15-00.327614556Z--d9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3
    78    [x] 0x086278A6C067775F71d6B2BB1856Db6E28c30418
    79      URL: keystore://$HOME/.core/devin/keystore/UTC--2018-02-06T22-53-11.211657239Z--086278a6c067775f71d6b2bb1856db6e28c30418
    80  -------------------------------------------
    81  Request context:
    82  	NA -> NA -> NA
    83  
    84  Additional HTTP header data, provided by the external caller:
    85  	User-Agent:
    86  	Origin:
    87  Approve? [y/N]:
    88  >
    89  ```
    90  
    91  Depending on whether we approve or deny the request, the original NetCat process will get:
    92  
    93  ```text
    94  {"jsonrpc":"2.0","id":1,"result":["0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3","0x086278a6c067775f71d6b2bb1856db6e28c30418"]}
    95  
    96  or
    97  
    98  {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Request denied"}}
    99  ```
   100  
   101  Apart from listing accounts, you can also *request* creating a new account; signing transactions and data; and recovering signatures. You can find the available methods in the Clef [External API Spec](https://github.com/core-coin/go-core/v2/tree/master/cmd/clef#external-api-1) and the [External API Changelog](https://github.com/core-coin/go-core/v2/blob/master/cmd/clef/extapi_changelog.md).
   102  
   103  *Note, the number of things you can do from the External API is deliberately small, since we want to limit the power of remote calls by as much as possible! Clef has an [Internal API](https://github.com/core-coin/go-core/v2/tree/master/cmd/clef#ui-api-1) too for the UI (User Interface) which is much richer and can support custom interfaces on top. But that's out of scope here.*
   104  
   105  ## Automatic rules
   106  
   107  For most users, manually confirming every transaction is the way to go. However, there are cases when it makes sense to set up some rules which permit Clef to sign a transaction without prompting the user. One such example would be running a signer on PoA networks.
   108  
   109  For starters, we can create a rule file that automatically permits anyone to list our available accounts without user confirmation. The rule file is a tiny JavaScript snippet that you can program however you want:
   110  
   111  ```js
   112  function ApproveListing() {
   113      return "Approve"
   114  }
   115  ```
   116  
   117  Of course, Clef isn't going to just accept and run arbitrary scripts you give it, that would be dangerous if someone changes your rule file! Instead, you need to explicitly *attest* the rule file, which entails injecting its hash into Clef's secure store.
   118  
   119  ```text
   120  $ sha256sum rules.js
   121  645b58e4f945e24d0221714ff29f6aa8e860382ced43490529db1695f5fcc71c  rules.js
   122  
   123  $ clef attest 645b58e4f945e24d0221714ff29f6aa8e860382ced43490529db1695f5fcc71c
   124  Decrypt master seed of clef
   125  Password:
   126  INFO [07-01|13:25:03.290] Ruleset attestation updated              sha256=645b58e4f945e24d0221714ff29f6aa8e860382ced43490529db1695f5fcc71c
   127  ```
   128  
   129  At this point, we can start Clef with the rule file:
   130  
   131  ```text
   132  $ clef --keystore ~/.core/devin/keystore --networkid 3 --rules rules.js
   133  
   134  INFO [07-01|13:39:49.726] Rule engine configured                   file=rules.js
   135  INFO [07-01|13:39:49.726] Starting signer                          networkid=4 keystore=$HOME/.core/devin/keystore light-kdf=false advanced=false
   136  DEBUG[07-01|13:39:49.726] FS scan times                            list=35.15µs set=4.251µs diff=2.766µs
   137  DEBUG[07-01|13:39:49.727] Ledger support enabled
   138  INFO [07-01|13:39:49.728] Audit logs configured                    file=audit.log
   139  DEBUG[07-01|13:39:49.728] IPC registered                           namespace=account
   140  INFO [07-01|13:39:49.728] IPC endpoint opened                      url=$HOME/.clef/clef.ipc
   141  ------- Signer info -------
   142  * intapi_version : 7.0.0
   143  * extapi_version : 6.0.0
   144  * extapi_http : n/a
   145  * extapi_ipc : $HOME/.clef/clef.ipc
   146  ```
   147  
   148  Any account listing *request* will now be auto-approved by the rule file:
   149  
   150  ```text
   151  $ echo '{"id": 1, "jsonrpc": "2.0", "method": "account_list"}' | nc -U ~/.clef/clef.ipc
   152  {"jsonrpc":"2.0","id":1,"result":["0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3","0x086278a6c067775f71d6b2bb1856db6e28c30418"]}
   153  ```
   154  
   155  ## Under the hood
   156  
   157  While doing the operations above, these files have been created:
   158  
   159  ```text
   160  $ ls -laR ~/.clef/
   161  
   162  $HOME/.clef/:
   163  total 24
   164  drwxr-x--x   3 user user  4096 Jul  1 13:45 .
   165  drwxr-xr-x 102 user user 12288 Jul  1 13:39 ..
   166  drwx------   2 user user  4096 Jul  1 13:25 02f90c0603f4f2f60188
   167  -r--------   1 user user   868 Jun 28 13:55 masterseed.json
   168  
   169  $HOME/.clef/02f90c0603f4f2f60188:
   170  total 12
   171  drwx------ 2 user user 4096 Jul  1 13:25 .
   172  drwxr-x--x 3 user user 4096 Jul  1 13:45 ..
   173  -rw------- 1 user user  159 Jul  1 13:25 config.json
   174  
   175  $ cat ~/.clef/02f90c0603f4f2f60188/config.json
   176  {"ruleset_sha256":{"iv":"SWWEtnl+R+I+wfG7","c":"I3fjmwmamxVcfGax7D0MdUOL29/rBWcs73WBILmYK0o1CrX7wSMc3y37KsmtlZUAjp0oItYq01Ow8VGUOzilG91tDHInB5YHNtm/YkufEbo="}}
   177  ```
   178  
   179  In `$HOME/.clef`, the `masterseed.json` file was created, containing the master seed. This seed was then used to derive a few other things:
   180  
   181  - **Vault location**: in this case `02f90c0603f4f2f60188`.
   182     - If you use a different master seed, a different vault location will be used that does not conflict with each other (e.g. `clef --signersecret /path/to/file`). This allows you to run multiple instances of Clef, each with its own rules (e.g. mainnet + testnet).
   183  - **`config.json`**: the encrypted key/value storage for configuration data, currently only containing the key `ruleset_sha256`, the attested hash of the automatic rules to use.
   184  
   185  ## Advanced rules
   186  
   187  In order to make more useful rules - like signing transactions - the signer needs access to the passwords needed to unlock keys from the keystore. You can inject an unlock password via `clef setpw`.
   188  
   189  ```text
   190  $ clef setpw 0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3
   191  
   192  Please enter a password to store for this address:
   193  Password:
   194  Repeat password:
   195  
   196  Decrypt master seed of clef
   197  Password:
   198  INFO [07-01|14:05:56.031] Credential store updated                 key=0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3
   199  ```
   200  
   201  Now let's update the rules to make use of the new credentials:
   202  
   203  ```js
   204  function ApproveListing() {
   205      return "Approve"
   206  }
   207  
   208  function ApproveSignData(req) {
   209      if (req.address.toLowerCase() == "0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3") {
   210          if (req.messages[0].value.indexOf("bazonk") >= 0) {
   211              return "Approve"
   212          }
   213          return "Reject"
   214      }
   215      // Otherwise goes to manual processing
   216  }
   217  ```
   218  
   219  In this example:
   220  
   221  - Any requests to sign data with the account `0xd9c9...` will be:
   222      - Auto-approved if the message contains `bazonk`,
   223      - Auto-rejected if the message does not contain `bazonk`,
   224  - Any other requests will be passed along for manual confirmation.
   225  
   226  *Note, to make this example work, please use you own accounts. You can create a new account either via Clef or the traditional account CLI tools. If the latter was chosen, make sure both Clef and Gocore use the same keystore by specifying `--keystore path/to/your/keystore` when running Clef.*
   227  
   228  Attest the new rule file so that Clef will accept loading it:
   229  
   230  ```text
   231  $ sha256sum rules.js
   232  f163a1738b649259bb9b369c593fdc4c6b6f86cc87e343c3ba58faee03c2a178  rules.js
   233  
   234  $ clef attest f163a1738b649259bb9b369c593fdc4c6b6f86cc87e343c3ba58faee03c2a178
   235  Decrypt master seed of clef
   236  Password:
   237  INFO [07-01|14:11:28.509] Ruleset attestation updated              sha256=f163a1738b649259bb9b369c593fdc4c6b6f86cc87e343c3ba58faee03c2a178
   238  ```
   239  
   240  Restart Clef with the new rules in place:
   241  
   242  ```
   243  $ clef --keystore ~/.core/devin/keystore --networkid 3 --rules rules.js
   244  
   245  INFO [07-01|14:12:41.636] Rule engine configured                   file=rules.js
   246  INFO [07-01|14:12:41.636] Starting signer                          networkid=4 keystore=$HOME/.core/devin/keystore light-kdf=false advanced=false
   247  DEBUG[07-01|14:12:41.636] FS scan times                            list=46.722µs set=4.47µs diff=2.157µs
   248  DEBUG[07-01|14:12:41.637] Ledger support enabled
   249  INFO [07-01|14:12:41.638] Audit logs configured                    file=audit.log
   250  DEBUG[07-01|14:12:41.638] IPC registered                           namespace=account
   251  INFO [07-01|14:12:41.638] IPC endpoint opened                      url=$HOME/.clef/clef.ipc
   252  ------- Signer info -------
   253  * intapi_version : 7.0.0
   254  * extapi_version : 6.0.0
   255  * extapi_http : n/a
   256  * extapi_ipc : $HOME/.clef/clef.ipc
   257  ```
   258  
   259  Then test signing, once with `bazonk` and once without:
   260  
   261  ```
   262  $ echo '{"id": 1, "jsonrpc":"2.0", "method":"account_signData", "params":["data/plain", "0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3", "0x202062617a6f6e6b2062617a2067617a0a"]}' | nc -U ~/.clef/clef.ipc
   263  {"jsonrpc":"2.0","id":1,"result":"0x4f93e3457027f6be99b06b3392d0ebc60615ba448bb7544687ef1248dea4f5317f789002df783979c417d969836b6fda3710f5bffb296b4d51c8aaae6e2ac4831c"}
   264  
   265  $ echo '{"id": 1, "jsonrpc":"2.0", "method":"account_signData", "params":["data/plain", "0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3", "0x2020626f6e6b2062617a2067617a0a"]}' | nc -U ~/.clef/clef.ipc
   266  {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Request denied"}}
   267  ```
   268  
   269  Meanwhile, in the Clef output log you can see:
   270  ```text
   271  INFO [02-21|14:42:41] Op approved
   272  INFO [02-21|14:42:56] Op rejected
   273  ```
   274  
   275  The signer also stores all traffic over the external API in a log file. The last 4 lines shows the two requests and their responses:
   276  
   277  ```text
   278  $ tail -n 4 audit.log
   279  t=2019-07-01T15:52:14+0300 lvl=info msg=SignData   api=signer type=request  metadata="{\"remote\":\"NA\",\"local\":\"NA\",\"scheme\":\"NA\",\"User-Agent\":\"\",\"Origin\":\"\"}" addr="0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [chksum INVALID]" data=0x202062617a6f6e6b2062617a2067617a0a content-type=data/plain
   280  t=2019-07-01T15:52:14+0300 lvl=info msg=SignData   api=signer type=response data=4f93e3457027f6be99b06b3392d0ebc60615ba448bb7544687ef1248dea4f5317f789002df783979c417d969836b6fda3710f5bffb296b4d51c8aaae6e2ac4831c error=nil
   281  t=2019-07-01T15:52:23+0300 lvl=info msg=SignData   api=signer type=request  metadata="{\"remote\":\"NA\",\"local\":\"NA\",\"scheme\":\"NA\",\"User-Agent\":\"\",\"Origin\":\"\"}" addr="0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [chksum INVALID]" data=0x2020626f6e6b2062617a2067617a0a     content-type=data/plain
   282  t=2019-07-01T15:52:23+0300 lvl=info msg=SignData   api=signer type=response data=                                     error="Request denied"
   283  ```
   284  
   285  For more details on writing automatic rules, please see the [rules spec](https://github.com/core-coin/go-core/v2/blob/master/cmd/clef/rules.md).
   286  
   287  ## Gocore integration
   288  
   289  Of course, as awesome as Clef is, it's not feasible to interact with it via JSON RPC by hand. Long term, we're hoping to convince the general Core community to support Clef as a general signer (it's only 3-5 methods), thus allowing your favorite DApp, Metamask, MyCrypto, etc to request signatures directly.
   290  
   291  Until then however, we're trying to pave the way via Gocore. Gocore v1.9.0 has built in support via `--signer <API endpoint>` for using a local or remote Clef instance as an account backend!
   292  
   293  We can try this by running Clef with our previous rules on Devin (for now it's a good idea to allow auto-listing accounts, since Gocore likes to retrieve them once in a while).
   294  
   295  ```text
   296  $ clef --keystore ~/.core/devin/keystore --networkid 3 --rules rules.js
   297  ```
   298  
   299  In a different window we can start Gocore, list our accounts, even list our wallets to see where the accounts originate from:
   300  
   301  ```text
   302  $ gocore --devin --signer=~/.clef/clef.ipc console
   303  
   304  > xcb.accounts
   305  ["0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3", "0x086278a6c067775f71d6b2bb1856db6e28c30418"]
   306  
   307  > personal.listWallets
   308  [{
   309      accounts: [{
   310          address: "0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3",
   311          url: "extapi://$HOME/.clef/clef.ipc"
   312      }, {
   313          address: "0x086278a6c067775f71d6b2bb1856db6e28c30418",
   314          url: "extapi://$HOME/.clef/clef.ipc"
   315      }],
   316      status: "ok [version=6.0.0]",
   317      url: "extapi://$HOME/.clef/clef.ipc"
   318  }]
   319  
   320  > xcb.sendTransaction({from: xcb.accounts[0], to: xcb.accounts[0]})
   321  ```
   322  
   323  Lastly, when we requested a transaction to be sent, Clef prompted us in the original window to approve it:
   324  
   325  ```text
   326  --------- Transaction request-------------
   327  to:       0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3
   328  from:     0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3 [chksum ok]
   329  value:    0 ore
   330  energy:      0x5208 (21000)
   331  energyprice: 1000000000 ore
   332  nonce:    0x2366 (9062)
   333  
   334  Request context:
   335  	NA -> NA -> NA
   336  
   337  Additional HTTP header data, provided by the external caller:
   338  	User-Agent:
   339  	Origin:
   340  -------------------------------------------
   341  Approve? [y/N]:
   342  > y
   343  ```
   344  
   345  :boom:
   346  
   347  *Note, if you enable the external signer backend in Gocore, all other account management is disabled. This is because long term we want to remove account management from Gocore.*