【Python】randomのuniform

The uniform() method returns a random floating number between the two specified numbers (both included).

import random

print(random.uniform(20, 30))

$ python3 test.py
25.547661293351773
$ python3 test.py
27.825416674846192

【Python】listのappend

import json
class MyClass:
    def __init__(self, a, b):
        self.group = []
        self.a = a
        self.b = b

    def add(self):
        c = self.a + self.b
        self.group.append(c)
        print(self.group)

obj = MyClass(2, 4)
obj.add()
obj.add()

$ python3 test.py
[6]
[6, 6]

【Python】jsonのsort_keys

json.dumpする際に、sort_keysをTrueとすることで、dictionallyのkeyでソートする

import json
class MyClass:
    def __init__(self, a, c, b):
        self.a = a
        self.c = c
        self.b = b

obj = MyClass(2, 4, 6)

string = json.dumps(obj.__dict__)
print(string)

string = json.dumps(obj.__dict__, sort_keys=True)
print(string)

$ python3 test.py
{“a”: 2, “c”: 4, “b”: 6}
{“a”: 2, “b”: 6, “c”: 4}

なるほど、これで下のコードが何をやってるのか理解できたわ

import hashlib
import json
from datetime import datetime
import random

class Block:
    def __init__(self, index, previous_hash, timestamp, data, validator):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.validator = validator
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        block_dict = self.__dict__
        if 'hash' in block_dict:
            del block_dict['hash']
        block_string = json.dumps(block_dict, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

【Python】selfと__dict__

__dict__はオブジェクトが持つ属性とその値を格納する辞書を返す特殊属性
モジュール、クラス、インスタンスなどで参照可能

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(2, 4)
print(obj.__dict__)

$ python3 test.py
{‘x’: 2, ‘y’: 4}

追加、更新、削除も可能

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(2, 4)
print(obj.__dict__)

obj.__dict__['z'] = 3
print(obj.__dict__)

obj.__dict__['x'] = 10
print(obj.__dict__)

del obj.__dict__['y']
print(obj.__dict__)

$ python3 test.py
{‘x’: 2, ‘y’: 4}
{‘x’: 2, ‘y’: 4, ‘z’: 3}
{‘x’: 10, ‘y’: 4, ‘z’: 3}
{‘x’: 10, ‘z’: 3}

dictはdictionallyの略ですね。__init__と__dict__が同時に出ると、やや混乱しましたが、使い方を理解すれば合点行きます。

【Python】classとself

initがコンストラクターとなり、selfはオブジェクト自身を表す

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def share_self(self):
        print("名前:", self.name)
        print("年齢:", self.age, '歳')

person_1 = Person('田中', 18)
person_2 = Person('山田', 20)

person_1.share_self()
person_2.share_self()

$ python3 test.py
名前: 田中
年齢: 18 歳
名前: 山田
年齢: 20 歳

【Python】hashdigest()

エンコードしたテキストをsha256でハッシュ化

import hashlib

text = "bbb"
encode_string = text.encode()
print(hashlib.sha256(encode_string).hexdigest())

$ python3 test.py
3e744b9dc39389baf0c5a0660589b8402f3dbb49b89b3e75f2c9355852a3c677

ubuntuでdocker版のcore lightningを動かしたい

// docker install
$ sudo snap install docker
docker 27.2.0 from Canonical✓ installed
$ docker -v
Docker version 27.2.0, build 3ab4256

// swap領域を作ります。
$ sudo fallocate -l 2G /swapfile2 # 2GBのファイルをアロケーション
$ sudo chmod 600 /swapfile2 # rootのみ読み書き可能に設定
$ sudo mkswap /swapfile2 # swap領域として設定
$ sudo swapon /swapfile2 # swap領域としてマウント
$ swapon -s
$ sudo vim /etc/fstab
$ grep swapfile /etc/fstab

$ free
total used free shared buff/cache available
Mem: 984504 372044 257744 1020 520044 612460
Swap: 2097148 0 2097148

// bitcoindのコンテナ起動
$ sudo docker pull lnbook/bitcoind
$ sudo docker run -it –name bitcoind lnbook/bitcoind
$ sudo docker exec -it bitcoind /bin/bash
$ sudo docker exec bitcoind cli getblockchaininfo
{
“chain”: “regtest”,
“blocks”: 1361,
“headers”: 1361,
“bestblockhash”: “72ec0a455c88d88b1d2c075949a76f6f133d92bca1c785a218b1cad48e7d6d71”,
“difficulty”: 4.656542373906925e-10,
“mediantime”: 1732410688,
“verificationprogress”: 1,
“initialblockdownload”: false,
“chainwork”: “0000000000000000000000000000000000000000000000000000000000000aa4”,
“size_on_disk”: 409811,
“pruned”: false,
“softforks”: {
“bip34”: {
“type”: “buried”,
“active”: true,
“height”: 500
},
“bip66”: {
“type”: “buried”,
“active”: true,
“height”: 1251
},
“bip65”: {
“type”: “buried”,
“active”: true,
“height”: 1351
},
“csv”: {
“type”: “buried”,
“active”: true,
“height”: 432
},
“segwit”: {
“type”: “buried”,
“active”: true,
“height”: 0
},
“testdummy”: {
“type”: “bip9”,
“bip9”: {
“status”: “active”,
“start_time”: 0,
“timeout”: 9223372036854775807,
“since”: 432
},
“height”: 432,
“active”: true
},
“taproot”: {
“type”: “bip9”,
“bip9”: {
“status”: “active”,
“start_time”: -1,
“timeout”: 9223372036854775807,
“since”: 0
},
“height”: 0,
“active”: true
}
},

// c-ligtningのコンテナ
$ sudo docker pull lnbook/c-lightning
$ sudo docker network ls
NETWORK ID NAME DRIVER SCOPE
ed2cf947ecfc bridge bridge local
1084f0825797 host host local
33d37569378e none null local
$ sudo docker network create lnbook
c2bf06e84e5437bcfa5469e80db47761dc1f6ebc4cb3a7b5dfd887d8f1ba2926

// bitcoindとc-lightningのコンテナを実行する
$ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
61c370e783cc lnbook/bitcoind “/usr/local/bin/bitc…” 45 minutes ago Exited (130) About a minute ago bitcoind
$ sudo docker rm bitcoind
bitcoind

$ sudo docker run -it –network lnbook –name bitcoind lnbook/bitcoind
// 別のターミナルでc-lightningのコンテナを起動
$ sudo docker run -it –network lnbook –name c-lightning lnbook/c-lightning
Waiting for bitcoind to start…
Waiting for bitcoind to mine blocks…
Starting c-lightning…
2024-11-24T01:25:55.433Z UNUSUAL lightningd: Creating configuration directory /lightningd/regtest
Startup complete
Funding c-lightning wallet
c17e6f647d5f9de7cfd92f71d764e13301e6ef6d6813c434480c27382d88e720
2024-11-24T01:25:55.433Z DEBUG lightningd: Opened log file /lightningd/lightningd.log
….
2024-11-24T01:27:26.866Z DEBUG lightningd: Adding block 230: 02b1a36fafcb73a47a6c45f832473532840bc8e8240a1fa482b80461443b04a1
2024-11-24T01:27:26.878Z DEBUG lightningd: Adding block 231: 2998734a84e2c45853c43f8ff384c7ea317b811b866b5d0426901fb12fbdf708
2024-11-24T01:27:26.891Z DEBUG lightningd: Adding block 232: 617b5c3a487f1035bd17d997a55466910ab5098ee0d9832d2607532dc95b1422
2024-11-24T01:27:26.904Z DEBUG lightningd: Adding block 233: 1781cdc3987abb38cafb7ba0c56bb9995df5ecba4896f47085bd6fd7e8a24bb4

おおおおおおおおおお
vagrant上では動かなかったけど、vps上では動いたぁああああああああああああ

Bitcoin CLIを触ってみる

まずbitcoincoreをpruneモードで起動します。
$ bitcoin-core.daemon -testnet -prune=550

サーバ側でTCPの8332ポートを開ける設定を行います

$ bitcoin-core.cli createwallet “testwallet”
error: timeout on transient error: Could not connect to the server 127.0.0.1:8332

Make sure the bitcoind server is running and that you are connecting to the correct RPC port.

あれ? bitcoindがrunning出ないと、cliの操作も当然できない

$ bitcoin-core.daemon -testnet -prune=550
メモリが足りずに固まってしまう。swapでメモリを上げないとダメか…
それにしても、bitcoincoreを稼働するには、cpu, メモリ, ネットワーク帯域など色々な問題があって、なかなか個人では難しいな…

ubuntuにcore lightningをインストール

$ cat /etc/os-release
PRETTY_NAME=”Ubuntu 24.04 LTS”
NAME=”Ubuntu”
VERSION_ID=”24.04″
//
$ sudo apt-get update
$ sudo apt install snapd
$ sudo snap install hello-world
$ hello-world
Hello World!
$ sudo snap install bitcoin-core
bitcoin-core 27.1 from Bitcoin Core installed

core-lightningに必要なライブラリをインストールする
$ sudo apt-get install –no-install-recommends –allow-unauthenticated python3 git make automake autoconf libtool build-essential libprotobuf-c-dev libsodium-dev libsqlite3-dev libgmp-dev libsqlite3-dev git net-tools valgrind curl ca-certificates jq
$ sudo apt install python3-pip

ソースコードをDL
$ git clone https://github.com/ElementsProject/lightning.git lightningd
$ cd lightningd && ls
CHANGELOG.md bitcoin configure flake.nix poetry.lock
Cargo.lock ccan conftest.py gossipd pyproject.toml
Cargo.toml ccan_compat.h connectd hsmd tests
Dockerfile channeld contrib lightningd tools
LICENSE cli db mkdocs.yml wallet
Makefile cln-grpc devtools nix wire
README.md cln-rpc doc onchaind
SECURITY.md closingd external openingd
action.yml common flake.lock plugins
$ ./configure
$ make

>> makoがないとエラーになるので、makoをインストールする
$ sudo apt-get install python3-mako
$ make

>> /bin/sh: 2: xgettext: not found
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install gettext libgettextpo-dev
$ make

>> No module named ‘grpc_tools’
$ sudo apt-get install python3-grpc-tools
$ make

>> Missing value for flag: –experimental_allow_proto3_optional
うーん、 解決できん…

というか、core lightningってcliベースでfundを開いたり、paymentを実行したりするのね…