Manage multiple jdks in macos, M1

First, install jenv by using Homebrew

1
brew install jenv

After that, need to config the zsh

1
2
3
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(jenv init -)"' >> ~/.zshrc
source ~/.zshrc

It only found the system default Java:

1
jenv versions

Add the jdk you installed to the jenv. Personally my jdks are installed at /Users/klam/Library/Java/JavaVirtualMachines/

For example:

jenv add /Users/klam/Library/Java/JavaVirtualMachines/azul-17.0.3/Contents/Home/

jenv global 17 to swap between different jdk for the default jdk

you can also use jenv local 17 to specifies the Java version of a folder

Java Error and exception

There are two type of Error in Java 1. “Error” , 2. “Exception”.

Error is something that fatel error such as problem of JVM itself or stackoverflow etc. In this case, just let the system down.

Exception is something due to programme and user’s normal problem, such as read a non-exist file, user input error etc. That can be handled by try-catch-code.

Session and Token

Introduction

I am working with a login api, and therefore I have some notes about Session and Token (JWT - Json web token).

Session

The general practice of a login system should be to verify that the customer’s login information is correct. Then add a logged in attribute to the client’s session if it is correct. There are usually some tools that help us doing that. Generally the default name of the session(cookie) is “JSESSIONID”; Stored in the client’s cookie, so we don’t have to write any more complicated operations in the program.

Each time the Client Side send a request, we bring the session id along with it. Server side will take the session ID and find out the specific session from the many sessions stored in Server.
There it is, if there are 10000 user online, server need to store 10000 different session in the database. Which is a very high IO, also, there is also the problem of how to share sessions between multiple hosts.

To solve this problem, we normally use Redis.

JWT token

It is very popular to use JWT as a Token instead of session. jwt is a string encrypted by the server and issued to the client.
After receiving the token, the client sends a request with the token in case of need, so that the Server can decrypt and verify the identity.
Because the token itself stores the authentication information of the client. In general, the Server will no longer store the token after it is issued.
Note that, the token can actually be stored in a cookie.

JWT implementation

There are three part of a JWT, header, payload, signature

The whole thing will use base64 encode

  • alg: Cryptographic algorithms used
  • typ: JWT

Payload

  • iss: Issuer
  • sub: subject, can be the key value such as account no.
  • exp: expiration time

Signature

sign(hash(header+payload))

The signature also certifies that only the party holding the private key is the one that signed it.

Generating JWT

1
2
3
4
5
6
7
8
9
// JWT code here
Date expireDate = new Date(System.currentTimeMillis()+30*60*1000);

String jwtToken = Jwts.builder().setSubject(email)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, "secret")
.compact();

return jwtToken;

Check the token

  • notes 1 : Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following: Authorization: Bearer <token>
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
public class AuthorizationCheckFilter extends OncePerRequestFilter{

@Override
`protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
if(!req.getServletPath().equals("/api/v1/user/login")){


String authorHeader = req.getHeader(AUTHORIZATION);
String bearer ="Bearer "; // notes 1

if(authorHeader!= null && authorHeader.startsWith(bearer)){
try{
String token = authorHeader.substring(bearer.length());
Claims claims = Jwts.parser().setSigningKey("MySecret")
.parseClaimsJws(token).getBody();

System.out.println("JWT payload:"+claims.toString());

chain.doFilter(req, res);

}catch(Exception e){
System.err.println("Error : "+e);
res.setStatus(FORBIDDEN.value());

Map<String, String> err = new HashMap<>();
err.put("jwt_err", e.getMessage());
res.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(res.getOutputStream(), err);
}
}else{
res.setStatus(UNAUTHORIZED.value());
}
}else{
chain.doFilter(req, res);
}

}

}

The jwt implementation of nestjs
https://github.com/etklam/nestjs-jwt-implementation

Spring Boot notes1 - Database and CURD

This notes is the learning process of Spring boot. Follow the https://www.udemy.com/course/spring-hibernate-tutorial/learn/lecture/12940996#overview

Connect to database

in the Resource path, there are a application.properties

input the JDBC properties

1
2
3
4
5
6
#
# JDBC properties

spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
spring.datasource.username=<username>
spring.datasource.password=<assword>

Create Entity

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
@Entity
@Table(name="employee")
public class Employee {

// define fields

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@Column(name="email")
private String email;


// define constructors

public Employee() {

}

public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

//define getter setter toString...
}

Hibernate implementation

Create a interface in src/java/projectname/dao/EmployeeDAO

DAO aka Data Access Object, is the “model” of MVC.

1
2
3
4
5
6
7
8
9
10
11
public interface EmployeeDAO {

public List<Employee> findAll();

public Employee findById(int theId);

public void save(Employee theEmployee);

public void delete(Employee theEmployee);

}

Implementing the interface in src/java/projectname/dao/EmployeeDAOHibernateImpl

@Repository

contains the api to control the database;
-. createQuery(…)

  • .get(…)
  • etc…

@Transactional

transaction is atom unit of the DBMS, Provides a way for database operation sequences to recover from failure to a normal state.
DBMS needs to ensure that all operations in the transaction are completed successfully and the results are permanently stored in the database.
IF some operations in the transaction are not completed successfully, all operations in the transaction need to be rolled back to the state before the transaction has no effect on the database or the execution of other transactions, and all transactions needs to be executed independently.

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

// repository contains the api to control the database;
@Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO {

// define field for entitymanager
private EntityManager entityManager;

// set up constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}


@Override
@Transactional
public List<Employee> findAll() {

// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);

// create a query
Query<Employee> theQuery =
currentSession.createQuery("select e from Employee e", Employee.class);

// execute query and get result list
List<Employee> employees = theQuery.getResultList();

// return the results
return employees;
}

@Override
public Employee findById(int theId) {
Session currentSession = entityManager.unwrap(Session.class);

Employee theEmployee = currentSession.get(Employee.class, theId);
return theEmployee;
}

@Override
public void save(Employee theEmployee) {
Session currentSession = entityManager.unwrap(Session.class);

currentSession.saveOrUpdate(theEmployee);
}

@Override
public void delete(Employee theEmployee) {
Session currentSession = entityManager.unwrap(Session.class);

currentSession.delete(theEmployee);
}

}

Service

Mostly similar to the dao, first create a interface, then implementing the interface.

1
2
3
4
5
6
7
8
9
10
public interface EmployeeService {

public List<Employee> findAll();

public Employee findById(int theId);

public void save(Employee theEmployee);

public void deleteById( int theId);
}
1
2
3
4
5

@Service
public class EmployeeServiceImpl implements EmployeeService {
...
}

Rest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/api")
public class EmployeeRestController {
private EmployeeService employeeService;

@Autowired
public EmployeeRestController(EmployeeService theEmployeeService) {
employeeService = theEmployeeService;
}

@GetMapping("/employees")...
@PostMapping("/employees")...
@GetMapping("/employees/{employeeId}")
@PutMapping("/employees")
@DeleteMapping("/employees/{employeeId}")
...
}

Blockchain key takeaway

Cryptography

  • Symmetric encryption (base on substitution and permutation): a secret key and an encryption algorithm
  • Asymmetric encryption (base on exponential): public key and private key system.
  • Public-key: provide confidentiality(encryption/decryption) and authentication (signature)
  • Both of them are secure and useful in diff scenarios
  • RSA algorithm is based on the difficulty of factoring problem.
  • Hash function can be applied to any sized message and produce fixed length message digest.
  • Sign the message digest instead of the message itself.
    • first hash the message
    • Then encrypt(sign) the hashed value
    • The message usually longer than the key size
  • DSA signature is based on the difficulty of discrete logarithms problem.

AES

permutation (shift rows)

AES key will be expanded(x11)
16bytes -> 176bytes
The chiper consists of N rounds, N depends on the key length:

  • 16bytes: 10rounds
  • 24bytes: 12rounds
  • 14bytes: 14rounds

Certification Authority (CA)

Sign certificate that bind subscriber’s name and his public key.
Indicates that the subscriber has sole control and access to the corresponding private key.

Public Key Infarstructure (PKI)

A set of policy, processes, server platforms, software etc…
to administer certificates

  • issue
  • maintain
  • revoke

Bitcoin

  • Merkle Tree Root is public for Verification
  • Merkle Tree Root for txs, and store in the block header
  • non-singular elliptic curve is the set of points and the point at infinity O
  • The point at infinity O is the identity elements
  • Bitcoin use Mudulo p - secp256k1, ECDSA

Bitcoin structure

Header:

  • Version Number
  • Hash of prev block header (by SHA256 double hash)
  • Hash of Transactions(merkle tree)
  • timestamp
  • Threshold(difficulty)
  • Nonce any value

Body:

  • Number of TXs
  • Coinbase
  • Regulars etc

Hash function Requirment

  • Easy to compute but diffcult to invert
  • Collision resistant

New diffculty caluate

Bitcoin create once every 10 minutes
Update the diffculty every 2016 blocks
T-new = T-sum/(2016*10*60) * T

Simple Payment Verification Node (SPV)

only stores the block header, contact full nodes when information needed.

Mining

read my code

Probability that the block hash falls below the target threshold T:
p= T+1/2^256

Lock Time

>= 510^8, it is a Unix time
< 5
10^8, it is a block blockHeight

  • Bitcoin prevents double spending(verifty every single node) and tampering(unless 51%)
  • Mining difficulty adjucted to regulate coin supply
  • Bitcoin address are shared over the internet

ETH

Account based model instead of UTXO. Main a global state to record the account balance

Accounts in ETH

Externally owned Accounts(EOA)

  • Controlled by private key
  • Has an Ether balance
  • no code

Contract Accounts

  • Has balance
  • Has code (smart contract)
  • has own permanent state

ETH Contact Transaction

  1. Create new contract
  2. Message the contract to execute it

Gas fee, Gas limit

Gas fee is the price per gas unit. Different operation cost different unit of gas.
Gas limit is the most you are willing to paid. The remainer will refund

ETH storage management - Radix Trie and Patricia Trie

—— Skip ——

  • State Trie
  • Transaction Trie
  • Receipts Trie

ETH consensus - simpler GHOST

Uncle Block: floked block. Give reward to honest but unlucky minor.

intrinsic reward = 5

If include a uncle block, minor can get extra 1/32 intrinsic reward.
Uncle can get depands on block height
(Uncle + 8 - block that include uncle)* intrinsic reward/8

Incentive: reward unluck but honest miners. Make it more fair.

Solidity simplest form notes

  • require The require function call defines conditions that reverts all changes if not met
  • emit an event after successful money transfer

Token

can be programmed to provide different functions

Initial Coin Offering (ICO)

raise funds for a company to create a new coins. similar to IPO

Consensus

PoW

  • the longest chain wins
  • the one growing fastest will be the longest and most trustworthy
  • take a lot of time to generate a block
  • if too easy, the chain can be DDoS attack
  • Huge Energy Consumption

PoS

  • creator of a block chosen in a random way, depending on the user’s wealth
  • In order to validate, forger must first put their own coin at “stake”.
  • When folk, pos vote

Randomized Block Selection

randomizaion to generate the following forger. Not true random in computer world. So is usually able to predict which user will be selected to forge the next block.

Coin Age Based selection

coin age = time * amount

Target * CoinAge = the hash difficulty.

To join the PoS, you might load your coins to other or join the pool youself.

Nothing at stake

when folk, vote for both because it gains most benefits. Always win, nothing to lose.
The blockchain might never reach Consensus
Use casper: punish

DPoS Delegated Proof of stake

vote to elect witnesses
21-100 elected witnesses in a DPoS. time slots are given to each witness to publish their block.
Longest chain wins
Much faster than POW and POS

Byzantine Fault Torlerance

  1. Commander -> all traitor
  2. traitor boardcast -> other traitor
  3. consensus

Consensus if at least 3m+1 nodes can achieve consensus. M is malicious nodes

Oral Message

  1. All messages are delivered correctly
  2. Know who this message is from
  3. Missing messages can be detected

Permissioned Blockchain

  • Regulation
  • Complete control of their data
  • Can be fully centralizated. Members negotiate.

Membership Service Providers (MSPs)

PKI and CA

Endorsement and validation policy can be adjusted as need.

  1. Client -> Endorser (proposal)
  2. Endorser check the certificate and others to validate the transactions
  3. Executes the chaincode
  4. Enderser -> Client
  5. Client -> Orderer
  6. Orderer include the transaction and generate blocks
  7. Orderer -> Anchor
  8. Anchor -> boardcast the block
  9. Peer verify the new block
  10. Peer -> Client

Channel

Maintan a Ledger, only nodes in channel can access this ledger.

Collection

The data on the chain can be said to be “permanent” and “public” to be shared among the participants. However, in the real application scenario, many data are not “publicly” stored in the blockchain due to privacy.
Only the header is stored on chain for verification.

Config wireguard with csf

Config wireguard with csf

csfpre.sh

CSF blocks Wireguard traffic, so we need to add some rules to iptables. Here are the instructions on how to do it.

Create a csfpre.sh file in the CSF path, for example, /etc/csf/csfpre.sh.
csfpre.sh adds iptable rules to CSF before it launches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
# iptables -A INPUT -p all -m set --match-set hkip src -j ACCEPT

iptables -A INPUT -i wg0 -j ACCEPT
iptables -A OUTPUT -o wg0 -j ACCEPT
iptables -A FORWARD -i wg0 -o ens3 -j ACCEPT
iptables -A FORWARD -i ens3 -o wg0 -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.7.0.2/24 -o ens3 -j MASQUERADE

# For ipv6, opional
ip6tables -A INPUT -i wg0 -j ACCEPT
ip6tables -A OUTPUT -o wg0 -j ACCEPT
ip6tables -A FORWARD -i wg0 -o ens3 -j ACCEPT
ip6tables -A FORWARD -i ens3 -o wg0 -j ACCEPT
ip6tables -t nat -A POSTROUTING -s fddd:2c4:2c4:2c4::2/64 -o ens3 -j MASQUERADE

en3 is your network interface
10.7.0.2/24 and fddd:2c4:2c4:2c4::2/64 is your wireguard internal ip.

Don’t forget to give permission to the script: chmod +x /etc/csf/csfpre.sh.

Finally, run:

csf -ra

wg0 configuration

add the follow line to the wg0.conf

1
2
PostUp = iptables -w -t nat -A POSTROUTING -o ens3 -j MASQUERADE; ip6tables -w -t nat -A POSTROUTING -o ens3 -j MASQUERADE
PostDown = iptables -w -t nat -D POSTROUTING -o ens3 -j MASQUERADE; ip6tables -w -t nat -D POSTROUTING -o ens3 -j MASQUERADE

Bitcoin implementation in typescript

Introduction

I am responsible for the transaction part in a group project about blockchain and bitcoin, and here is my code. Just for archive.

library

Bitcoin is using elliptic and secp256k1

1
2
3
4
import { SHA256 } from 'crypto-js';

var EC = require('elliptic').ec;
var ec = new EC('secp256k1');
1
2
3
4
5
6
7
8
9
10
11
12
export class Signature {
static sign(priKey: string, msg: string): string {
const key = ec.keyFromPrivate(priKey, 'hex');
const signature = key.sign(msg).toDER();
return signature;
}

static verify(pubKey: string, sig: string, msg: string): boolean {
const key = ec.keyFromPublic(pubKey, 'hex');
return key.verify(msg, sig);
}
}

Class in a Transaction

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

export class RegularTxIn extends TxIn {
txOutId: string;
txOutIndex: number;
signature: string;

constructor(txOutId: string, txOutIndex: number, priKey) {
super();
this.txOutId = txOutId;
this.txOutIndex = txOutIndex;
this.signature = this.createSig(priKey, this.msgHash());
}

createSig(priKey: string, msg: string): string {
return Signature.sign(priKey, msg);
}

msgHash(): string {
return SHA256(SHA256(this.txOutId + this.txOutIndex)).toString();
}
}

export class CoinbaseTxIn extends TxIn {
public blockHeight: number;

constructor(blockHeight: number) {
super();
this.blockHeight = blockHeight;
}
}

export class RegularTxIn extends TxIn {
txOutId: string;
txOutIndex: number;
signature: string;

constructor(txOutId: string, txOutIndex: number, priKey) {
super();
this.txOutId = txOutId;
this.txOutIndex = txOutIndex;
this.signature = this.createSig(priKey, this.msgHash());
}

createSig(priKey: string, msg: string): string {
return Signature.sign(priKey, msg);
}

msgHash(): string {
return SHA256(SHA256(this.txOutId + this.txOutIndex)).toString();
}
}

export class CoinbaseTxIn extends TxIn {
public blockHeight: number;

constructor(blockHeight: number) {
super();
this.blockHeight = blockHeight;
}
}

export class TxOut {
address: string; //public key
amount: number;

constructor(address: string, amount: number) {
this.address = address;
this.amount = amount;
}
}

export class UTXO {
txId: string;
txOut: TxOut;
txIndex: number;

constructor(txId: string, txOut: TxOut, txIndex: number) {
this.txId = txId;
this.txOut = txOut;
this.txIndex = txIndex;
}
}

Transaction Class

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
export class Transaction {
type: string;
id: string;
txIns: TxIn[];
txOuts: TxOut[];

constructor(ins: TxIn[], outs: TxOut[]) {
this.txIns = ins;
this.txOuts = outs;
this.id = this.setId();
}

setId(): string {
let txInContent: string;
if (this instanceof RegularTx) {
txInContent = this.txIns
.map((regularTxIn: RegularTxIn) => regularTxIn.txOutId + regularTxIn.txOutIndex)
.reduce((a, b) => a + b, '');
} else {
txInContent = this.txIns
.map((coinbaseTxIn: CoinbaseTxIn) => coinbaseTxIn.blockHeight)
.reduce((a, b) => a + b, '');
}

const txOutContent: string = this.txOuts
.map((txOuts: TxOut) => txOuts.address + txOuts.amount)
.reduce((a, b) => a + b, '');

return SHA256(SHA256(txInContent + txOutContent)).toString();
}

public static createRegularTx(
senderPubKey: string,
senderPriKey: string,
receiverPubKey: string,
receiveAmount: number,
fee: number,
) {
const utxo = this.findUTXO(senderPubKey);
let sumUTXO = 0;
const txIns = [];
const txOuts = [];
let i = 0;
utxo.forEach((val) => {
//the sum of UTXO of a pubkey
sumUTXO += val.amount;
// Create input object for each UTXO, sign the input by user private key
i++;
txIns.push(new RegularTxIn(val.id, i, senderPriKey));
});
const totalAmountToSpend = receiveAmount + fee;
if (sumUTXO < totalAmountToSpend) {
// Not enough money
return; //exception
}
for (let n = 0; n < txIns.length; n++) {
// verify the input by signature
const checker = Signature.verify(utxo[i].address, txIns[i].signature, txIns[i].msgHash());
if (!checker) {
return; //exception
}
}
//Create out put to receiver by PP2K
txOuts.push(new TxOut(receiverPubKey, receiveAmount));
//return change to the sender
const change = sumUTXO - receiveAmount - fee;
if (change > 0) {
txOuts.push(new TxOut(senderPubKey, change));
}
const tx = new Transaction(txIns, txOuts);
// tx.setId()
return tx;
}

public static findUTXO(senderPubKey) {
const allBlock = [];
const allTxOut = [];
const allTxIn = [];
allBlock.forEach((block) => {
const txs = block.txs;
txs.forEach((tx) => {
const txOuts = tx.txOuts;
txOuts.forEach((out) => {
if (out.address == senderPubKey) {
allTxOut.push(out);
}
});
});
});
return [];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export class RegularTx extends Transaction {
type: 'regular';
txIns: RegularTxIn[];

constructor(ins: RegularTxIn[], outs: TxOut[]) {
super(ins, outs);
}
}

export class CoinBaseTx extends Transaction {
type: 'coinbase';
txIns: CoinbaseTxIn[];

constructor(ins: CoinbaseTxIn, outs: TxOut[]) {
super([ins], outs);
}
}

Create Transaction and UTXO

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public async createTx(
senderPubKey: string,
senderPriKey: string,
receiverPubKey: string,
receiveAmount: number,
fee: number,
) {
const utxos = await this.getUXTO(senderPubKey);
let sumUTXO = 0;

const txIns = utxos.map((tx) => {
sumUTXO += tx.txOut.amount;
return new RegularTxIn(tx.txId, tx.txIndex, senderPriKey);
});

const txOuts = [];

const totalAmountToSpend = receiveAmount + fee;

if (sumUTXO < totalAmountToSpend) {
// Not enough money
throw new Error('Insufficient Balance'); //exception
}

for (let i = 0; i < txIns.length; i++) {
// verify the input by signature
// TODO: check if utxos[i].txOut.address is correct or not
const checker = Signature.verify(utxos[i].txOut.address, txIns[i].signature, txIns[i].msgHash());

if (!checker) {
throw new Error('Invalid txIns'); //exception
}
}

//Create out put to receiver by PP2K
txOuts.push(new TxOut(receiverPubKey, receiveAmount));
//return change to the sender
const change = sumUTXO - receiveAmount - fee;
txOuts.push(new TxOut(senderPubKey, change));

const tx = new RegularTx(txIns, txOuts);
tx.setId();

this.broadcast(tx);
await this.transactionPoolService.addTransaction(tx);

return tx;
}

public async getAllUTXO(): Promise<UTXO[]> {
const outs: UTXO[] = [];
// loop all the blocks
for (let i = 0; i < this.blockService.getBlockHeight(); i++) {
const currentBlockHash = this.blockService.getBlockHash(i);
const currentBlock = await this.blockService.getBlock(currentBlockHash);
const currentTx = currentBlock.data.transactions; // need to convert to list of Transaction

// loop all the transaction
currentTx.forEach((currentTx) => {
const txID = currentTx.id;
const txOuts = currentTx.txOuts;
const txIns = currentTx.txIns;

// Create UTXO object for each TxOutPut, push to UTXO
txOuts.forEach((txOut, i) => {
outs.push(new UTXO(txID, txOut, i)); // create UTXO obj that store tx, txid and index
});

// Remove the spent money
txIns.forEach((tx) => {
if (tx instanceof RegularTxIn) {
const outID = tx.txOutId;
const outIndex = tx.txOutIndex;
const indexOfTx = outs.findIndex((obj) => {
return obj.txId == outID && obj.txIndex == outIndex;
});

if (indexOfTx >= 0) {
outs.splice(indexOfTx, 1);
}
}
});
});
}
return outs;
}

public async getUXTO(pubKey: string): Promise<UTXO[]> {
const allUtxo = await this.getAllUTXO();

return allUtxo.filter((tx) => {
return tx.txOut.address === pubKey;
});
}


IT Auditing notes 2

Operation Control

Segregation of Duties

Avoid single person could be responsible for diverse and critical functions. Otherwise, error or misappropriation could occur and not be detected in a timely manner and in normal course of business processes.

Incident handling

identify when where whole

Shadow IT: IT users at an organisation electing to use tools and services that have not been officially sanctioned by said organisation.

  • Converage - insurance?
  • Action - what to do?
  • Evidence
  • Tasks to do during recovery

Management of removable media and system documentation

Monitoring

  • audit logging
  • Clock Synchronize

Logical Controls

Concurrent Sign-on Session

can be very useful, but also a control weaknesses

Suggestion:

  • No or only few user can have concurrent
  • No more than two
  • Logged and reviewed

Remote access Control

  • Deducated leased liveness
  • VPN
  1. Identification process (username?)
  2. Authentication process (password?)
  3. Permitted/denied

Input Control

source document design - arrange fields for ease of use.

Software development Control

  • Business realization: 個system點幫到公司
  • project management
    • Cost and resource/ Deliverable/Time(Duration)
  • System development approach SDLC approaches
    • SDLC: 流水線

IT Auditing notes 1

The structure of an IT Audit

Phase 1 - Audit Planning Phase

In this phase, auditor review controls such as General Controls and application controls. After that, plan tests of controls and substantive testing procedures.

Phase 2 - Test of Control

Perform tests of control -> Evaluate Test result -> Determine degree of reliance on controls.

Phase 3 - Substantive Testing Phase

Perform Substantive Tests -> Evaluate Result -> issue audit report

PDC Control Models

Preventive 預防

Detective 監察

Corrective 執屎

Internal Control Activities

  • Independent verification
  • Transaction Authorization
  • Segregation of duties
  • Supervision
  • Audit trail provision

Physical Control

Provision of a secure area - Security perimeter

Prevent unauthorized access

  • Physical lock : Conventional keys/Electronic access badge system/cipher lock
  • Selection and design of secure areas
  • intruder detection system(Camera)
  • Sperate from 3rd party area and public area detection
  • backup
  • loading area

backup

  • Full backup
  • Incremental backup
    • Cumulative incremental: Since last full backup
    • Differentail incremental: Since last backup(any type)

Resumption programs

Hot Site - full equipped and can be operational in less than 24 hours
Cold site -
Partner with other companies

Risk Analysis

Step 1 - identify Threats and Risks

  • Threat Agents: 觸發threats既人or物 fire/hacker/employee/…
  • Weaknesses: 弱點
  • Risks: weaknesses引致既後果

Step 2 - Quantify Impact of potential Threats

Single Loss Expectancy(SLE) + Annualized frequency = Annual Loss Expectancy(ALE)

Select a counter measurement

Cost/benefits calculation:

ALE before implementing safety measure - ALE after implenting safety measure - annual cost of safeguard = value of safefuard to the company

Javascript callback promise await/async

I have been coding in JavaScript for a while now, but I realized that I didn’t have a solid understanding of how the language works. This was a surprising realization, considering how much time I spend working with it. So, to improve my skills, I decided to do some research and dive deeper into the workings of JavaScript.

JavaScript is a programming language designed to run on client-side browsers. In this context, everything related to the internet is unpredictable. For example, if an image is too large, the browser can get stuck, and that’s where callback functions come in.

A callback function is a function that’s passed as an argument to another function. It’s used to execute code asynchronously, which means that the program doesn’t stop until the function is executed entirely. The concept of a callback is that we put the functions that need time to run into a “Callback Queue” and continue running the following code. This allows us to avoid blocking the program while it waits for the function to finish running.

Another useful feature of JavaScript is the Promise object. A promise is an object that includes a resolve and reject function. The resolve function is called when the code runs successfully, while the reject function is called when the code throws an error. We use try-catch blocks to handle errors in promises.

Async/Await is another feature of JavaScript that’s used for clean code. The await keyword is used in the async function to pause the function until the Promise is resolved or rejected. We can use this feature to write asynchronous code that looks like synchronous code, which makes the code easier to read and understand.

In summary, JavaScript is a powerful language that’s essential for web development. Understanding its features, including callback functions, Promises, and Async/Await, is crucial for writing efficient and clean code.

Callback

The concept of callback is that, we put the functions that needs time to run into a “Callback Queue”, and continue run the following code.

Promise

Promise is object that include resolve and reject, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
let p = new Promise(function(resolve, reject) {
if(){
resolve();
}else{
reject;
}
})

p.then(function(){
// resolve
}).catch(function() {
// return a exception, and catch the error
})

Async Await

The await must be in the async function

1
2
3
4
5
6
7
8
9
async function getSomething(){
try{
let something = await fetch(url);
console.log(something)
}
catch( exception ){
console.log(exception)
}
}

Async await is usually the better for clean code.