flask入門

$ flask –version
Python 3.8.10
Flask 2.0.2
Werkzeug 2.0.2

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
	return '<html><body><h1>sample</h1></body></html>'

if __name__ == '__main__':
	app.run(debug=True, host='192.168.33.10', port=8000)

template/index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type=text/css href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
	<header>
		<div class="navbar navbar-dark bg-dark box-shadow">
            <div class="container d-flex justify-content-between">
                <a href="/" class="navbar-brand d-flex align-items-center">
                    <strong>サンプル</strong>
                </a>
            </div>
        </div>
	</header>
	<div class="content container">
		<h2>値の表示</h2>
        <p>値1:{{ values.val1 }}</p>
        <p>値2:{{ values.val2 }}</p>
	</div>
</body>
</html>

app.py

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
	values = {"val1": 100, "val2": 200}
	return render_template("index.html", values=values)

if __name__ == '__main__':
	app.run(debug=True, host='192.168.33.10', port=8000)

[Rust] Basic 1: variable and array

### variables

fn main() {
    let x = 13;
    println!("{}", x);

    let x: f64 = 3.14159;
    println!("{}", x);

    let x;
    x = 0;
    println!("{}", x);
}

$ target/debug/hello
13
3.14159
0

variables are modifiable.
mutable: compiler allows read and write
immutable: the compiler will only allow the variable to be read from
mutable values are denoted with a mut keyword.

fn main() {
    let mut x = 42;
    println!("{}", x);
    x = 13;
    println!("{}", x);
}

booleans: bool
unsigned integers(符号なし): u8, u16, u32, u64, u128
signed integers(符号あり): i8, i16, i32, i64, i128
pointer sized integers: usize, isize
floating point: f32, f64
tuple: (value, value, …)
arrays:
slices,
str
Numeric types can be explicitly specified by appending the type to the end of the number.(13u32, 2u8)

fn main() {
    let x = 12;
    let a = 12u8;
    let b = 4.3;
    let c = 4.3f32;
    let bv = true;
    let t = (13, false);
    let sentence = "hello world";
    println!(
    	"{} {} {} {} {} {} {} {}",
    	x, a, b, c, bv, t.0, t.1, sentence
    )
}

$ target/debug/hello
12 12 4.3 4.3 true 13 false hello world

### Basic Type Conversion
as で変換する

fn main() {
    let a = 13u8;
    let b = 7u32;
    let c = a as u32 + b;
    println!("{}", c);

    let t = true;
    println!("{}", t as u8);
}

$ target/debug/hello
20
1

### constants
constant used many times efficiently.
constant must always have explicit types.
constant names are always in SCREAMING_SNAKE_CASE.

const PI: f32 = 3.14159;

fn main() {
    println!(
    	"to make an apple {} from scratch, you must first create a universe.",
    	PI
    )
}

const PI: u8 = 12; とも書く

### Arrays
an array is a fixed length collection of data.
data type for an array is [T;N] where T is the elements type and N is the fixed length.
Individual elements can be retrieved with the x operator

fn main() {
    let nums: [i32; 3] = [1, 2, 3];
    println!("{:?}", nums);
    println!("{}", nums[1]);
}

$ target/debug/hello
[1, 2, 3]
2

なるほど

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