[Klaytn 사용기]Caver가 뭐야? -1

Junho Bae·2020년 11월 13일
0
post-thumbnail

이더리움 스마트 컨트랙트를 배포하고 웹 프로젝트에서 블록체인과 소통하기 위해서는 web3.js 라이브러리를 사용하곤 했었습니다. 클레이튼 역시 클레이튼 노드와 상호작용할 수 있는 라이브러리인 caver를 제공하고 있습니다. 클레이튼 docs의 caver-js 시작하기를 한번 진행해 보려고 합니다. 👍

caver는 js, java로 사용 가능합니다. 이번 포스트에서는 caver-js를 살펴보겠습니다. caver-js는 npm 이용이 가능합니다.

출처: 클레이튼 DOCS


caver-js의 패키지

  1. caver.account
  2. caver.wallet.keyring
  3. caver.wallet
  4. caver.transaction
  5. caver.rpc
  6. caver.contract
  7. caver.abi
  8. caver.kct
  9. caver.utils
  10. caver.ipfs

시작하기

caver-js 라이브러리를 사용하려면 node.js, npm, gcc-c++, Solidity Compiler가 준비되어 있어야 합니다.

준비가 되었다면, npm init을 실행하고 caver를 install 합니다.

npm install caver-js

이제 Klaytn Wallet에서 생성할 수 있는 본인의 keystore file을 이용해서 klay 전송 트랜잭션을 살펴볼 것입니다. keystore file은 Klaytn Wallet을 참고하면 아주 간단하게 만들수가 있답니다😊.

노드에 접속하기

const Caver = require('caver-js')
const caver = new Caver('https://api.baobab.klaytn.net:8651/')

async function testFunction() {
    const version = await caver.rpc.klay.getClientVersion()
    console.log(version)
}

testFunction()

caver-js 모듈을 받아와서 baobab(klaytn testnet)의 노드에 접속합니다. 이후 버전을 확인합니다.

이렇게 버전이 잘 나온다면 성공입니다.

keyring 관리

keyring은 Klaytn account의 주소와 private key(s)를 담고 있는 구조체입니다. 크게 세가지로 분류가 됩니다.

  1. SingleKeyring : 하나의 주소와 하나의 private key
  2. MultipleKeyring : 하나의 주소와 여러개의 private keys. 구조체 안에 keys라는 배열이 있고 그 안에 여러개의 private keys를 담고 있음.
  3. RoleBasedKeyring : 하나의 주소와 하나 이상의 각각의 role에 맞는 private keys. keys라는 속성이 2차원 배열로 구성. ([],[],[]) 이런 식인데 그 안에 각각의 role에 맞는 key들이 들어감. 첫 번째부터, roleTransactionKey, roleAccountUpdateKey, roleFeePayerKey의 순서로 들어감.

이제 각각의 keyring을 생성하는 코드들을 살펴보겠습니다.

SingleKeyring 만들기

const Caver = require('caver-js')
const caver = new Caver('https://api.baobab.klaytn.net:8651/')

async function testFunction() {
    const keyring = caver.wallet.keyring.generate()
    console.log(keyring)
}

testFunction()

코드에서 caver.wallet.keyring.generate()을 사용해서 현재 임의의 SingleKeyring을 생성할 수 있습니다.

다음과 같은 코드에서는 본인의 개인키를 이용해서 Keyring을 만들 수도 있습니다.

const Caver = require('caver-js')
const caver = new Caver('https://api.baobab.klaytn.net:8651/')

async function testFunction() {
    // Create a keyring from a private key
    const keyringFromPrivateKey = caver.wallet.keyring.createFromPrivateKey('0x{private key}')
    console.log(keyringFromPrivateKey)
}

testFunction()

createFromPrivateKey에 파라미터로 본인의 PK를 넘겨주면 됩니다.

개인키와 계정 주소로 SingleKeyring 생성하기

만약 Klaytn 계정 주소가 개인키로부터 생성된 것이 아닌, 개인키와 별도로 분리된 것이라면 주소와 개인키를 사용해서 Keyring을 만들 수 있습니다.

async function testFunction() {
    const keyring = caver.wallet.keyring.createWithSingleKey('0x{address in hex}', '0x{private key}')
    console.log(keyring)

    const keyringFromKlaytnWalletKey = caver.wallet.keyring.createFromKlaytnWalletKey('0x{private key}0x{type}0x{address in hex}')
    console.log(keyringFromKlaytnWalletKey)
}

caver.wallet.keyring.createFromKlaytnWalletKey는 Klaytn Wallet Key Format을 인자로 받습니다. 이는 private key가 그에 해당되는 address와 함께 관리될 수 있게 하는 구조라고 합니다.
*여기서 type에는 00가 들어가야 합니다.

이렇게 잘 뜨는걸 확인할 수가 있습니다.

MultipleKeyring

뭐 지금까지 했던 것 처럼 각 caver의 모듈을 써서 keyfing을 만드는 방법들이 소개됩니다.

  1. MultipleKeyring
async function testFunction() {
    const keyring = caver.wallet.keyring.createWithMultipleKey('0x{address in hex}', [ '0x{private key1}', '0x{private key2}' ])
    console.log(keyring)
}
  1. RoleBasedKeyring
async function testFunction() {
defined by each roles
    const keyring = caver.wallet.keyring.createWithRoleBasedKey('0x{address in hex}', [
        [ '0x{private key1}', '0x{private key2}', '0x{private key3}' ],
        [ '0x{private key4}'],
        [ '0x{private key5}', '0x{private key6}' ],
    ])
    console.log(keyring)
}

그렇...다고합니다.

caver-js에 Keyring 추가하기

async function testFunction() {
    // Using a keyring instance
    const keyring = caver.wallet.keyring.generate()
    caver.wallet.add(keyring)
    console.log(caver.wallet.getKeyring(keyring.address))

    // Using a keystore file
    const decrypted = caver.wallet.keyring.decrypt({ 
        version: 4,
        id: '9c12de05-0153-41c7-a8b7-849472eb5de7',
        address: '0xc02cec4d0346bf4124deeb55c5216a4138a40a8c',
        keyring: [
            { 
                ciphertext: 'eacf496cea5e80eca291251b3743bf93cdbcf7072efc3a74efeaf518e2796b15',
                cipherparams: { iv: 'd688a4319342e872cefcf51aef3ec2da' },
                cipher: 'aes-128-ctr',
                kdf: 'scrypt',
                kdfparams: {
                    dklen: 32,
                    salt: 'c3cee502c7157e0faa42386c6d666116ffcdf093c345166c502e23bc34e6ba40',
                    n: 4096,
                    r: 8,
                    p: 1
                },
                mac: '4b49574f3d3356fa0d04f73e07d5a2a6bbfdd185bedfa31f37f347bc98f2ef26'
            }
        ]
    }, 'password')

    caver.wallet.add(decrypted)
    console.log(caver.wallet.getKeyring(decrypted.address))
}

코드상에서는 처음에 임의의 값으로 keyring을 생성해서 인 메모리 wallet에 추가하고 다음에는 본인의 keystore 파일을 사용해서 추가합니다.

저같은 경우에는 klaytn wallet에서 받은 keystore파일을 열어서 포맷을 살짝 맞추었더니 프로그램이 정상 작동 하기는 합니다..ㅎ

마지막 인자인 'password'가 klatyn wallet 생성할때 설정한 password가 들어가야 합니다.

사실 Keyring 추가는 address와 private key가 있으면 caver.wallet.newKeyring을 사용해서 쉽게 wallet에 추가할 수 있다는데요.

그걸 왜 이제..

async function testFunction() {
    // Add to wallet with an address and a private key
    const addedSingle = caver.wallet.newKeyring('0x{address in hex}', '0x{private key1}')
    console.log(caver.wallet.getKeyring(addedSingle.address))

    // Add to wallet with an address and private keys
    const addedMultiple = caver.wallet.newKeyring('0x{address in hex}', ['0x{private key2}', '0x{private key3}', '0x{private key4}'])
    console.log(caver.wallet.getKeyring(addedMultiple.address))

    // Add to wallet with an address and private keys defined by each roles
    const addedRoleBased = caver.wallet.newKeyring('0x{address in hex}', [
        ['0x{private key5}', '0x{private key6}', '0x{private key7}'],
        ['0x{private key8}', '0x{private key9}'],
        ['0x{private key10}', '0x{private key11}']
    ])
    console.log(caver.wallet.getKeyring(addedRoleBased.address))
}

private key의 특성에 따라서 적절한 keyring이 생성되고 지갑에 추가가 된다고 합니다(..)

profile
SKKU Humanities & Computer Science

0개의 댓글