feat(cli)_: add a command 'server-account' to be able to re-run existing accounts (#5329)

* feat(cli)_: add a command 'servelast' to be able to run the latest account.

Reason: because on testing community join req/response we only want to create a community by a cli and remain the owner over multiple runs

* fix_: allow restarting cli with the same account

* docs_: add use cases to readme

* docs(cli)_: typos

* fix(cli)_: typo

* docs(cli)_: add clarifications
This commit is contained in:
Pablo Lopez 2024-06-12 11:00:51 +03:00 committed by GitHub
parent 892fcffce4
commit ea5c444dbe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 302 additions and 42 deletions

View File

@ -38,6 +38,9 @@ JSON RPC examples:
# get waku info
curl -XPOST http://127.0.0.1:8545 -H 'Content-type: application/json' -d '{"jsonrpc":"2.0","method":"waku_info","params":[],"id":1}'
# get peer info
curl --request POST --url http://127.0.0.1:8545 --header 'Content-type: application/json' --data '{"jsonrpc": "2.0", "method": "wakuext_peers", "params": [], "id": 1}'
# send contact request from charlie to alice (use -a flag will automatacally send contact request when starting)
curl -XPOST http://127.0.0.1:8565 -H 'Content-type: application/json' -d '{"jsonrpc":"2.0","method":"wakuext_sendContactRequest","params":[{"id": "0x0436470da23039f10c1588bc6b9fcbd4b815bf9fae4dc09c0fb05a7eaaf1670b5dbdbc757630d54bf2f8be45a796304dc42506c3f4172f499f610a9ed85d9b0d4c", "message": "hello"}],"id":1}'
@ -48,8 +51,17 @@ curl -XPOST http://127.0.0.1:8565 -H 'Content-type: application/json' -d '{"json
curl -XPOST http://127.0.0.1:8545 -H 'Content-type: application/json' -d '{"jsonrpc":"2.0","method":"wakuext_sendOneToOneMessage","params":[{"id": "0x042c0ce856c41ad6d3f651a84c83f646cdafdf3a26a3d69bce3a6ccf59b23b5a366c12162045d5066abad7912741a6e6c6e8e11e7826c4c850a1de7a2bae24a79c", "message": "Im fine, and you?"}],"id":1}'
```
### Run `serve-account` command
### Run `simulate` command:
The `./status-cli serve` command will generate a new account, it will print in the console the key UID of that account, if you want to re-run that created account (i.e.: run the account with the same public key), you can do so with this command:
```bash
./status-cli serve-account -n alice -kid 0x02887ff8dddb774ad836c00c8fd30ef9bc45d6b23f1f8cad1bff07d09cb378c3
```
You will need the same name and key
### Run `simulate` command
```bash
# simulate DM between two accounts
@ -67,4 +79,175 @@ curl -XPOST http://127.0.0.1:8545 -H 'Content-type: application/json' -d '{"json
You can run the commands with `--light` to work as a light client.
Logs are recorded in file `*.log` and terminal.
Logs are recorded in file `*.log` and terminal.
## JSON-RPC use cases
### Start two CLIs adding each other as contacts
```bash
# terminal 1 (alice)
./status-cli serve -n alice -p 5500
# note the public key and the key id from the output
# terminal 2 (bobby)
./status-cli serve -n bobby -p 5501 -a <alice_pub_key>
```
## Restart any existing account
```bash
# notice we need both the name and the key id (not the pub key here)
# the key id will be pressent in the logs when a new account is created, same as the public key
./status-cli serve -n bobby -kid <bob_key_id>
```
### Create community
Have two CLIs running (`alice` and `bobby`)
```bash
# 1. (alice) create community
# this call will return the community id
curl --request POST \
--url http://127.0.0.1:5500/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_createCommunity",
"params": [
{
"membership": 3,
"name": "cli-test-1",
"color": "#ffffff",
"description": "cli-test-1"
}
],
"id": 1
}'
# 2. (bobby & alice) fetch community (use communityId from step 1 response)
curl --request POST \
--url http://127.0.0.1:5501/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_fetchCommunity",
"params": [
{
"communityKey": "0x02bea5af5779d5f742f2419cc0d819d3ce33adb922e8e90bdf3533fd121d52d4bc",
"waitForResponse": true,
"tryDatabase": true
}
],
"id": 1
}'
# 3. (bobby) request to join community (use communityId from step 1 response)
# this call will return the requestsToJoinCommunity.id
curl --request POST \
--url http://127.0.0.1:5501/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_requestToJoinCommunity",
"params": [
{
"communityId": "0x02bea5af5779d5f742f2419cc0d819d3ce33adb922e8e90bdf3533fd121d52d4bc"
}
],
"id": 1
}'
# 4. (alice) accept request to join community from bobby (use requestsToJoinCommunity.id from step 3 response)
# in the response you can see the community id and the chats' ids for that community ($.result.communities[*].chats[*].id)
curl --request POST \
--url http://127.0.0.1:5500/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_acceptRequestToJoinCommunity",
"params": [
{
"id": "0x1b828fe8c778403268ffcf80b892f8be46cf9a85ba2c9f479bfb0c0a807a71f4"
}
],
"id": 1
}'
# 5. (alice) send chat message (bobby should receive it)
# chatId is the community id concatenated to the chat id (from step 4 response)
curl --request POST \
--url http://127.0.0.1:5500/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_sendChatMessage",
"params": [
{
"chatId": "0x02bea5af5779d5f742f2419cc0d819d3ce33adb922e8e90bdf3533fd121d52d4bcdfe601d1-096c-4201-b692-fcdb81ef0cec",
"text": "hello there",
"contentType": 1
}
],
"id": 1
}'
# 6. (bobby) leave the community (use communityId from step 1 response)
curl --request POST \
--url http://127.0.0.1:5501/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_leaveCommunity",
"params": [
"0x02bea5af5779d5f742f2419cc0d819d3ce33adb922e8e90bdf3533fd121d52d4bc"
],
"id": 1
}'
# Optional:
# 7. (bobby & alice) fetch community again and verify the members (curl from step 2.)
# 8. Instead of creating a community always you can restart alice and bobby and proceed from step 2. Alice is the owner
```
### Private group chat
Have two CLIs running (`alice` and `bobby`)
```bash
# 1. (alice) create the group chat including bobby's public key in it,
# the response will have the group chat id to send messages to it
curl --request POST \
--url http://127.0.0.1:8545/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_createGroupChatWithMembers",
"params": [
null,
"group-chat-name",
[
"0x04d3c86dfc77b195b705e1831935066076018aa0d7c40044829801ebbfe9b06480ce4662072bf16a3ca7cb8f6289207614deceaf7d33e099dfc9281610375fec08"
]
],
"id": 1
}'
# 2. (alice) send the message to the id of the group chat (from step 1 response)
curl --request POST \
--url http://127.0.0.1:5500/ \
--header 'Content-type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "wakuext_sendGroupChatMessage",
"params": [
{
"id": "8291eae1-338c-4481-9997-04edd2d2bbed-0x0490cbce029eaf094c7f2dcf1feb2d60e91ab1498847eb29fa98cc5ea5a36666b3f9ada142f3080f5074abd942c863438f6af9475f30781790c7e36f9acd2ac93e",
"message": "hello"
}
],
"id": 1
}'
```

View File

@ -20,6 +20,7 @@ const AddFlag = "add"
const PortFlag = "port"
const APIModulesFlag = "api-modules"
const TelemetryServerURLFlag = "telemetry-server-url"
const KeyUIDFlag = "key-uid"
const RetrieveInterval = 300 * time.Millisecond
const SendInterval = 1 * time.Second
@ -109,7 +110,38 @@ func main() {
Usage: "Start a server to send and receive messages",
Flags: ServeFlags,
Action: func(cCtx *cli.Context) error {
return serve(cCtx)
return serve(cCtx, false)
},
},
{
Name: "serve-account",
Aliases: []string{"sl"},
Usage: "Start a server with the lastest input name's account\n\n E.g.: if last time you created an account with name 'Alice',\n you can start the server with 'Alice' account by running 'servelast -n Alice'",
Flags: []cli.Flag{
&cli.StringFlag{
Name: NameFlag,
Aliases: []string{"n"},
Usage: "Name of the existing user",
Required: true,
},
&cli.StringFlag{
Name: KeyUIDFlag,
Aliases: []string{"kid"},
Usage: "Key ID of the existing user (if not provided the last account will be used)",
},
&cli.BoolFlag{
Name: InteractiveFlag,
Aliases: []string{"i"},
Usage: "Use interactive mode to input the messages",
},
&cli.StringFlag{
Name: AddFlag,
Aliases: []string{"a"},
Usage: "Add a friend with the public key",
},
},
Action: func(cCtx *cli.Context) error {
return serve(cCtx, true)
},
},
},

View File

@ -16,7 +16,7 @@ import (
"go.uber.org/zap"
)
func serve(cCtx *cli.Context) error {
func serve(cCtx *cli.Context, useExistingAccount bool) error {
rawLogger, err := zap.NewDevelopment()
if err != nil {
log.Fatalf("Error initializing logger: %v", err)
@ -34,8 +34,9 @@ func serve(cCtx *cli.Context) error {
telemetryUrl := cCtx.String(TelemetryServerURLFlag)
interactive := cCtx.Bool(InteractiveFlag)
dest := cCtx.String(AddFlag)
keyUID := cCtx.String(KeyUIDFlag)
cli, err := start(name, port, apiModules, telemetryUrl)
cli, err := start(name, port, apiModules, telemetryUrl, useExistingAccount, keyUID)
if err != nil {
return err
}
@ -48,7 +49,7 @@ func serve(cCtx *cli.Context) error {
msignal.SetMobileSignalHandler(msignal.MobileSignalHandler(func(s []byte) {
var ev MobileSignalEvent
if err := json.Unmarshal(s, &ev); err != nil {
logger.Errorf("unmarshaling signal event: %v", err)
logger.Error("unmarshaling signal event", zap.Error(err), zap.String("event", string(s)))
return
}

View File

@ -39,13 +39,13 @@ func simulate(cCtx *cli.Context) error {
apiModules := cCtx.String(APIModulesFlag)
telemetryUrl := cCtx.String(TelemetryServerURLFlag)
alice, err := start("Alice", 0, apiModules, telemetryUrl)
alice, err := start("Alice", 0, apiModules, telemetryUrl, false, "")
if err != nil {
return err
}
defer alice.stop()
charlie, err := start("Charlie", 0, apiModules, telemetryUrl)
charlie, err := start("Charlie", 0, apiModules, telemetryUrl, false, "")
if err != nil {
return err
}

View File

@ -9,6 +9,7 @@ import (
"github.com/status-im/status-go/api"
"github.com/status-im/status-go/logutils"
"github.com/status-im/status-go/multiaccounts"
"github.com/status-im/status-go/protocol/requests"
"github.com/status-im/status-go/services/wakuv2ext"
@ -33,37 +34,26 @@ func setupLogger(file string) *zap.Logger {
return logutils.ZapLogger()
}
func start(name string, port int, apiModules string, telemetryUrl string) (*StatusCLI, error) {
namedLogger := logger.Named(name)
namedLogger.Info("starting messager")
_ = setupLogger(name)
path := fmt.Sprintf("./test-%s", strings.ToLower(name))
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
return nil, err
}
func start(name string, port int, apiModules string, telemetryUrl string, useExistingAccount bool, keyUID string) (*StatusCLI, error) {
var (
rootDataDir = fmt.Sprintf("./test-%s", strings.ToLower(name))
password = "some-password"
)
setupLogger(name)
nlog := logger.Named(name)
nlog.Info("starting messager")
backend := api.NewGethStatusBackend()
createAccountRequest := &requests.CreateAccount{
DisplayName: name,
CustomizationColor: "#ffffff",
Emoji: "some",
Password: "some-password",
RootDataDir: fmt.Sprintf("./test-%s", strings.ToLower(name)),
LogFilePath: "log",
APIConfig: &requests.APIConfig{
APIModules: apiModules,
HTTPHost: "127.0.0.1",
HTTPPort: port,
},
TelemetryServerURL: telemetryUrl,
}
_, err = backend.CreateAccountAndLogin(createAccountRequest)
if err != nil {
return nil, err
if useExistingAccount {
if err := getAccountAndLogin(backend, name, rootDataDir, password, keyUID); err != nil {
return nil, err
}
} else {
acc, err := createAccountAndLogin(backend, name, rootDataDir, password, apiModules, telemetryUrl, port)
if err != nil {
return nil, err
}
nlog.Infof("account created, key UID: %v", acc.KeyUID)
}
wakuService := backend.StatusNode().WakuV2ExtService()
@ -73,25 +63,79 @@ func start(name string, port int, apiModules string, telemetryUrl string) (*Stat
wakuAPI := wakuv2ext.NewPublicAPI(wakuService)
messenger := wakuAPI.Messenger()
_, err = wakuAPI.StartMessenger()
if err != nil {
if _, err := wakuAPI.StartMessenger(); err != nil {
return nil, err
}
namedLogger.Info("messenger started, public key: ", messenger.IdentityPublicKeyString())
nlog.Info("messenger started, public key: ", messenger.IdentityPublicKeyString())
time.Sleep(WaitingInterval)
data := StatusCLI{
name: name,
messenger: messenger,
backend: backend,
logger: namedLogger,
logger: nlog,
}
return &data, nil
}
func getAccountAndLogin(b *api.GethStatusBackend, name, rootDataDir, password string, keyUID string) error {
b.UpdateRootDataDir(rootDataDir)
if err := b.OpenAccounts(); err != nil {
return fmt.Errorf("name '%v' might not have an account: trying to find: %v: %w", name, rootDataDir, err)
}
accs, err := b.GetAccounts()
if err != nil {
return err
}
if len(accs) == 0 {
return errors.New("no accounts found")
}
acc := accs[0] // use last if no keyUID is provided
if keyUID != "" {
found := false
for _, a := range accs {
if a.KeyUID == keyUID {
acc = a
found = true
break
}
}
if !found {
return fmt.Errorf("account not found for keyUID: %v", keyUID)
}
}
return b.LoginAccount(&requests.Login{
Password: password,
KeyUID: acc.KeyUID,
})
}
func createAccountAndLogin(b *api.GethStatusBackend, name, rootDataDir, password, apiModules, telemetryUrl string, port int) (*multiaccounts.Account, error) {
if err := os.MkdirAll(rootDataDir, os.ModePerm); err != nil {
return nil, err
}
req := &requests.CreateAccount{
DisplayName: name,
CustomizationColor: "#ffffff",
Emoji: "some",
Password: password,
RootDataDir: rootDataDir,
LogFilePath: "log",
APIConfig: &requests.APIConfig{
APIModules: apiModules,
HTTPHost: "127.0.0.1",
HTTPPort: port,
},
TelemetryServerURL: telemetryUrl,
}
return b.CreateAccountAndLogin(req)
}
func (cli *StatusCLI) stop() {
err := cli.backend.StopNode()
if err != nil {