/
keyring.go
56 lines (48 loc) · 1.4 KB
/
keyring.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package dockerutil
import (
"archive/tar"
"bytes"
"context"
"io"
"os"
"path"
"path/filepath"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/docker/docker/client"
)
// NewLocalKeyringFromDockerContainer copies the contents of the given container directory into a specified local directory.
// This allows test hosts to sign transactions on behalf of test users.
func NewLocalKeyringFromDockerContainer(ctx context.Context, dc *client.Client, localDirectory, containerKeyringDir, containerId string) (keyring.Keyring, error) {
reader, _, err := dc.CopyFromContainer(ctx, containerId, containerKeyringDir)
if err != nil {
return nil, err
}
if err := os.Mkdir(filepath.Join(localDirectory, "keyring-test"), os.ModePerm); err != nil {
return nil, err
}
tr := tar.NewReader(reader)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return nil, err
}
var fileBuff bytes.Buffer
if _, err := io.Copy(&fileBuff, tr); err != nil {
return nil, err
}
name := hdr.Name
extractedFileName := path.Base(name)
isDirectory := extractedFileName == ""
if isDirectory {
continue
}
filePath := filepath.Join(localDirectory, "keyring-test", extractedFileName)
if err := os.WriteFile(filePath, fileBuff.Bytes(), os.ModePerm); err != nil {
return nil, err
}
}
return keyring.New("", keyring.BackendTest, localDirectory, os.Stdin)
}