Ubuntu20.04 でRustの環境構築

$ curl –proto ‘=https’ –tlsv1.2 -sSf https://sh.rustup.rs | sh
$ sudo apt install cargo
$ cargo new –bin hello
$ cd hello
$ cargo build
Compiling hello v0.1.0 (/home/vagrant/dev/rust/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
│   ├── hello-2ab4b0e0c3958f3e
│   └── hello-2ab4b0e0c3958f3e.d
├── examples
├── hello
├── hello.d
└── incremental

7 directories, 8 files

$ target/debug/hello
Hello, world!

ファイルの中身を見てみる
hello/src/main.rs

fn main() {
    println!("Hello, world!");
}

中身をtour of rustと同じにする

fn main() {
    println!("Hello, 🦀");
}

$ cargo build
$ target/debug/hello
Hello, 🦀

なるほど…

Solanaとは?

Solanaは他のブロックチェーンより圧倒的に高速低コスト
ティッカーシンボル: SOL
レイヤー1のみで完結できる
他のブロックチェーンと相互運用ができる(Warmholeというイーサリアムとのブリッジ機能)
長期保有によるステーキング報酬を得られる

トランザクション処理:50,000/秒
トランザクション手数料: 0.00005ドル
ブロック生成速度: 0.4秒

Serumでエアドロップ、solanaでテザーがローンチ、NFTプロジェクト立ち上げ(猿の画像を買うのにSOLが必要) などで高騰

PoH(proof of history): timestampで証明
ステーキングとは一時的にロックさせる
インターオペラビリティ
Audius, Serum, LoanSnap, USDT, USDCと連携

https://solana.com/

solanaのblock chain engineerのjob opportunity
– Proficiency with systems level languages like Rust, C, C++
– Experience with smart contract development, distributed computing, and/or system design
– Exceptional quantitative and analytical skills – bonus if you’ve applied those to trading strategies in a professional capacity
– Belief in the benefits of open source contribution
– Passion for software development, DeFi, and cryptocurrencies

なるほどー、 solana作ってる奴らは皆んなRustやってるのか…

[Ethereum] SolidityのContractをweb3.jsで呼び出したい

<body>
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
	<script>
    const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/*"));
      const address = "*";
      const abi = [{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"clients","outputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"gender","type":"string"},{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"uint256","name":"height","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_gender","type":"string"},{"internalType":"uint256","name":"_weight","type":"uint256"},{"internalType":"uint256","name":"_height","type":"uint256"}],"name":"register","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"excesise","outputs":[{"internalType":"uint256","name":"newWeight","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]

      const contract = new web3.eth.Contract(abi, address);
      const handleCall = async () => {
        await contract.methods.register("tanaka", "aaa", 65, 175);
        const result = await contract.methods.excesise.call();
        console.log(result);
      };
      handleCall();
      
    </script>
</body>
</html>

{arguments: Array(0), call: ƒ, send: ƒ, encodeABI: ƒ, estimateGas: ƒ, …}

何故だろう… 期待通りにいかん…

[ethereum] solidityをRopstenにデプロイしたい

$ npm install truffle-hdwallet-provider
$ truffle compile

truffleconfig.js

const HDWalletProvider = require("truffle-hdwallet-provider");
const mnemonic = "";

    ropsten: {
      provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/${project_id}`),
      network_id: 3,       // Ropsten's id
      gas: 5500000,        // Ropsten has a lower block limit than mainnet
      confirmations: 2,    // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
    },

$ truffle migrate –network ropsten

なるほど、これは凄い

[ethereum] solidityで配列に格納して、値を返却する

Practice.sol
L 構造体Clientのclientsという配列に格納して、excesise関数でweightを-2として返却するコントラクトです。

pragma solidity >= 0.4.0 < 0.7.0;

contract Practice {

	struct Client {
		string name;
		string gender;
		uint256 weight;
		uint256 height;
	}
	Client[] public clients;

	function register(string memory _name, string memory _gender, uint256 _weight, uint256 _height) public returns(uint256 id) {
		id = clients.push(Client(_name, _gender, _weight, _height)) - 1;
		return id;
	}

	function excesise() public returns (uint256 newWeight){
		newWeight = clients[0].weight - 2;
		return newWeight;
	}

}

practice_test.js

	describe("practice()", () => {
		it("returns excesized weight", async() => {
			const practice = await PracticeContract.deployed();
			const expected = 63;
			await practice.register("yamada", "male", 65, 175);
			const actual = await practice.excesise.call();
			
			assert.equal(actual, expected, "Weight should be 63");
		})
	})

Contract: Practice
✓ has been deployed successfully
practice()
✓ returns weight (124ms)

2 passing (184ms)

[ethereum] solidityでtax計算

Practice.sol

contract Practice {

	function hello() external pure returns(string memory) {
		return "Hello, World!";
	}

	function tax(uint256 price) public pure returns(uint256 newPrice){
		 newPrice = price * 11 / 10;
		 return newPrice;
	}
}

practice_test.js

	describe("practice()", () => {
		it("returns tax in price", async() => {
			const practice = await PracticeContract.deployed();
			const expected = "110";
			const actual = await practice.tax(100);
			assert.equal(actual, expected, "should be 110");
		})
	})

$ truffle test

Compiling your contracts…
===========================
> Compiling ./contracts/Migrations.sol
> Compiling ./contracts/Practice.sol
> Artifacts written to /tmp/test-202209-108928-12xhvrv.xr0d
> Compiled successfully using:
– solc: 0.5.16+commit.9c3226ce.Emscripten.clang

Contract: Practice
✓ has been deployed successfully
practice()
✓ returns ‘Hello, World!’
practice()
✓ returns tax in price

3 passing (123ms)

taxのmultiplyは price * 1.1; とするとエラーになるので、price * 11 / 10;としないといけない。
なるほど、中々激しい。

opensslで暗号処理

バージョン確認
$ openssl version
OpenSSL 1.1.1f 31 Mar 2020

$ openssl enc
共通鍵暗号による暗号化と復号
ブロック暗号とストリーム暗号
ソルト、パディング、利用モード

-e: 暗号化
-d: 復号
-in: 入力ファイル(平文)
-out: 出力ファイル(暗号文)
-アルゴリズム: -aes256, -camellia256, -rc4など

-aes128
無線LANなどの通信データの暗号化に用いられる暗号化アルゴリズム。「Advanced Encryption Standard」の略
データの送信者と受信者が同じ暗号鍵を用いて、暗号化と復号を実行
128ビット長
通信データを区切り、置き換え・並べ替えのセットを複数回繰り返すアルゴリズム。最もセキュリティが強固。
base64はバイナリをエンコード

暗号化と復号化

$ echo '220104_input_text' | openssl enc -e -aes128 | base64
$ echo 'U2FsdGVkX1/miQdEamHLeWn5BmGbLJ3O+LpZTnWX8aRM1WSdbm6rr/2wZU68iqKZ' | openssl enc -d -aes128 -base64
enter aes-128-cbc decryption password:
*** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.
220104_input_text

crontabでModuleNotFoundError: No module named ‘mysql’

hoge.py

import requests
import mysql.connector
import config
from datetime import datetime
// 省略

$ sudo vi /etc/crontab

0 0    * * *   root    /usr/bin/python3 /home/ubuntu/hoge/cmd/hoge.py > /var/log/myjob.log 2>&1

$ cat /var/log/myjob.log
Traceback (most recent call last):
File “/home/ubuntu/reddit/cmd/_cardano.py”, line 2, in
import mysql.connector
ModuleNotFoundError: No module named ‘mysql’

なぜだあああああああああああ
2時間ぐらい格闘して

hoge.py

#!PYTHONPATH=/home/ubuntu/.local/lib/python3.8/site-packages
import requests
import mysql.connector
import config
from datetime import datetime

$ sudo service cron restart

これで上手くいった…

なぜ上手くいったのかさっぱりわからない….
とりあえずOKだわ、上手く動いているか明日再度確認する