---
title:
output:
  revealjs::revealjs_presentation:
    theme: white
    css: white-edits.css
    highlight: tango
    transition: fade
    transitionSpeed: fast
    self_contained: false
    reveal_options:
      minScale: 1.0
      maxScale: 1.0
      touch: false
    mathjax: "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
---

```{r, eval=FALSE, include=FALSE}
library(tm)
library(wordcloud)
setwd("D:/Dropbox/2017 Fall/Liang Seminar (CMU)/Week 2/Blockchain")
text <- read.csv("Data/text.txt", stringsAsFactors = FALSE)
corp <- Corpus(VectorSource(text$text))
corp = tm_map(corp, content_transformer(tolower))
corp = tm_map(corp, removeNumbers)
corp = tm_map(corp, removePunctuation)
corp = tm_map(corp, removeWords, c("the", "and", stopwords("english")))
corp =  tm_map(corp, stripWhitespace)
tdm <- TermDocumentMatrix(corp)
tdm <- as.matrix(tdm)
v = sort(rowSums(tdm), decreasing = TRUE)
png("Figures/wordcloud.png", width = 3200, height = 2400, res=400)
wordcloud(names(v),v, width = 3200, height = 2400, res=400, colors = c("#8A704C22","#151C5522"), random.colors = FALSE, random.order = TRUE)
dev.off()
```


```{r blocks, eval=FALSE, include=FALSE}
setwd("D:/Dropbox/2017 Fall/Liang Seminar (CMU)/Week 2/Blockchain")
# download a few blocks to analyze, store them locally to save time/bandwidth
library(RCurl)
library(XML)
html1 <- getURL('https://webbtc.com/block/0000000000000000000cdc0d2a9b33c2d4b34b4d4fa8920f074338d0dc1164dc')
html2 <- getURL('https://webbtc.com/block/000000000000000001806a922d4d35a37ad9324c690f72d556c6445cb7a9c214')
html3 <- getURL('https://webbtc.com/block/000000000000000000f061205567dc79c4e718209a568879d66132e016968ac6')


extract_block <- function(html) {
  i <- 3
  j <- 1
  
  doc = htmlParse(html, asText=TRUE)
  
  edges = list(from=c(),to=c())
  nodes = list(id=c())
  
  xpath <- paste('/html/body/table[2]/tr[',toString(i),']/td[2]/table/tr[',toString(j),']/td[1]/a',sep='')
  
  while (!is.null(xpathSApply(doc, xpath, xmlValue))) {
    ins <- c()
    outs <- c()
    while (!is.null(xpathSApply(doc, xpath, xmlValue))) {
      plain.text <- xpathSApply(doc, xpath, xmlValue)
      val <- gsub("\n","",gsub(" ", "", paste(plain.text, collapse = ""), fixed = TRUE), fixed = TRUE)
      ins <- c(ins,val)
      j <- j + 1
      xpath <- paste('/html/body/table[2]/tr[',toString(i),']/td[2]/table/tr[',toString(j),']/td[1]/a/text()',sep='')
    }
    j <- 1
    xpath <- paste('/html/body/table[2]/tr[',toString(i),']/td[3]/table/tr[',toString(j),']/td[1]/a/text()',sep='')
    while (!is.null(xpathSApply(doc, xpath, xmlValue))) {
      plain.text <- xpathSApply(doc, xpath, xmlValue)
      val <- gsub("\n","",gsub(" ", "", paste(plain.text, collapse = ""), fixed = TRUE), fixed = TRUE)
      outs <- c(outs,val)
      j <- j + 1
      xpath <- paste('/html/body/table[2]/tr[',toString(i),']/td[3]/table/tr[',toString(j),']/td[1]/a/text()',sep='')
    }
    j <- 1
    i <- i + 1
    xpath <- paste('/html/body/table[2]/tr[',toString(i),']/td[2]/table/tr[',toString(j),']/td[1]/a/text()',sep='')
    # join lists
    temp <- expand.grid(from=ins,to=outs)
    edges$from = c(edges$from,as.character(temp$from))
    edges$to = c(edges$to,as.character(temp$to))
  }
  nodes$id <- unique(c(edges$to,edges$from))
  
  graph <- list(edges=edges, nodes=nodes)
  return(graph)
}
graph <- extract_block(html1)
nodes <- as.data.frame(graph$nodes,stringsAsFactors=FALSE)
edges <- as.data.frame(graph$edges,stringsAsFactors=FALSE)
nodes$title <- nodes$id
edges$arrows <- "to"
save(nodes,file="Data/nodes1.Rda")
save(edges,file="Data/edges1.Rda")
# load(file="Data/nodes1.Rda")
# load(file="Data/edges1.Rda")
# visNetwork(nodes,edges, width="100%", height="600px")

graph <- extract_block(html2)
nodes <- as.data.frame(graph$nodes,stringsAsFactors=FALSE)
edges <- as.data.frame(graph$edges,stringsAsFactors=FALSE)
nodes$title <- nodes$id
edges$arrows <- "to"
save(nodes,file="Data/nodes2.Rda")
save(edges,file="Data/edges2.Rda")
# load(file="Data/nodes2.Rda")
# load(file="Data/edges2.Rda")
# visNetwork(nodes,edges, width="100%", height="600px")


graph <- extract_block(html3)
nodes <- as.data.frame(graph$nodes,stringsAsFactors=FALSE)
edges <- as.data.frame(graph$edges,stringsAsFactors=FALSE)
nodes$title <- nodes$id
edges$arrows <- "to"
save(nodes,file="Data/nodes3.Rda")
save(edges,file="Data/edges3.Rda")
# load(file="Data/nodes3.Rda")
# load(file="Data/edges3.Rda")
# visNetwork(nodes,edges, width="100%", height="600px")

# load(file="Data/nodes1.Rda")
# load(file="Data/edges1.Rda")
# nodes1 <- nodes
# edges1 <- edges
# nodes1$group <- "First"
# edges1$group <- "First"
# load(file="Data/nodes2.Rda")
# load(file="Data/edges2.Rda")
# nodes2 <- nodes
# edges2 <- edges
# nodes2$group <- "Second"
# edges2$group <- "Second"
# load(file="Data/nodes3.Rda")
# load(file="Data/edges3.Rda")
# nodes3 <- nodes
# edges3 <- edges
# nodes3$group <- "Third"
# edges3$group <- "Third"
# rm(nodes)
# rm(edges)
# nodes <- rbind(nodes3,nodes2,nodes1)
# edges <- rbind(edges3,edges2,edges1)
# nodes <- nodes[!duplicated(nodes$id),]
# 
# visNetwork(nodes,edges, width="100%", height="600px") %>%
#   visGroups(groupname = "First", color = list(background = "#97C2FC", border = "#77A2DC")) %>%
#   visGroups(groupname = "Second", color = list(background = "#FCC297", border = "#DCA277")) %>% 
#   visGroups(groupname = "Third", color = list(background = "#C2FC97", border = "#A2DC77")) %>% 
#   visOptions(highlightNearest = list(enabled = T, degree = 2, hover = T),
#              nodesIdSelection = FALSE, selectedBy ="group") %>% 
#   visLegend()
```


```{r currencies, echo=FALSE, warning = FALSE, message = FALSE}
library(RCurl)
library(XML)
cryptoMC <- function(name) {
  if (exists(name)) {
    get(name)
  } else{
  html <- getURL(paste('https://coinmarketcap.com/currencies/',name,'/',sep=''))
  xpath <- '/html/body/div[3]/div/div[1]/div[4]/div[1]/div[1]/div[2]/text()'
  doc = htmlParse(html, asText=TRUE)
  plain.text <- xpathSApply(doc, xpath, xmlValue)
  assign(name, gsub("\n","",gsub(" ", "", paste(plain.text, collapse = ""), fixed = TRUE), fixed = TRUE),envir = .GlobalEnv)
  get(name)
  }
}
```

```{r btc_price, echo=FALSE, warning = FALSE, message = FALSE}

html <- getURL(paste('https://coinmarketcap.com/currencies/','bitcoin','/',sep=''))
xpath <- '//*[@id="quote_price"]'
doc = htmlParse(html, asText=TRUE)
plain.text <- xpathSApply(doc, xpath, xmlValue)
btc <- as.numeric(gsub("$","",gsub("\n","",gsub(" ", "", paste(plain.text, collapse = ""), fixed = TRUE), fixed = TRUE), fixed = TRUE))
```

## Blockchain {data-background-image="Figures/wordcloud-edit.png" class="title no-toc-progress" data-state="no-toc-progress"}

<h2 class="author"><br>Richard M. Crowley<br>Singapore Management University<br><br>Slides available at <a href="http://rmc.link/Bitcoin/Bitcoin.html">http://rmc.link/Bitcoin/Bitcoin.html</a><br>CPU friendly variant at <a href="http://rmc.link/Bitcoin/Bitcoin.html">http://rmc.link/Bitcoin/Bitcoin_light.html</a></h2>
<h3 class="date">November 2, 2017</h3>

Note: all prices as of `r format(Sys.time(), "%a %b %d %X %Y")`

# What is blockchain?

## Origins

- *Satoshi Nakamura* whitepaper, 2008
    - <a href="https://bitcoin.org/bitcoin.pdf">Bitcoin: A Peer-to-Peer Electronic Cash System</a>
- Blockchain is an underlying component of bitcoin
    - Open <a href="https://github.com/bitcoin/bitcoin">sourced code</a> in 2009
- Bitcoin was created as a *distributed* electronic payment system
    - Not a new idea, but an elegant implementation
    - Working distributed payment systems existed in 2007, were discussed in academic literature since 1998 or earlier
- Main issue with prior work: the double spending problem

## The double spending problem

> - Physical currency -- give to someone else
> - Debit card -- bank won't let you go below 0
> - Credit card -- payment processor and banks handle this
>     - Credit limits
>     - Legal measures 
> - Bitcoin
>     - Cryptographic proof of transaction
>     - Can be verified by anyone...
>         - Unless someone holds >50% of CPU power (majority attack)

# How does it work?

## Transactions

<img src="Figures/Bitcoin-cash.png" width="100%">

## Transactions

<img src="Figures/Bitcoin-cash_govt.png" width="100%">

## Transactions

<img src="Figures/Bitcoin-credit.png" width="100%">

## Transactions

<img src="Figures/Bitcoin-bitcoin.png" width="100%">

## Consequences of structure

- Everyone knows what your public key is tied to
    - No one knows who the key represents
    - Ex.: 1HB5XMLmzFVj8ALj6mfBsbifRoD4miY36v
- Transaction record is permanent
    - Can't be lost*
    - Can't be faked*
- The network acts as an escrow service of sorts
    - Charges a fee (<a href="https://bitcoinfees.earn.com/">0.0000026 BTC</a>, `r btc*0.0000026` USD)

## Where is it?

<div class="left">
Already in use:

- Cash (<a href="https://bitcoin.org/en/">Bitcoin</a>)
- Contracts (<a href="https://ethereum.org/">Ethereum</a>)
- Supply chains (<a href="https://www.ibm.com/blockchain/hyperledger.html">IBM Fabric</a> using <a href="https://www.hyperledger.org/">Hyperledger</a>, <a href="https://www.provenance.org/whitepaper">Provenance</a>)
- Exchanges: (<a href="https://www.coinbase.com/">Coinbase</a>)
- Data storage (<a href="https://sia.tech/">Sia</a>, <a href="https://filecoin.io/">Filecoin</a>)
- Finance (<a href="https://www.r3.com/">R3 Corda</a>)
- Property rights (<a href="https://www.factom.com/">Factom</a>)
</div>
<div class="right">
Working on it:

- Insurance (<a href="http://plex.ai/">Plex.ai</a>)
- Academic credentials (<a href="https://www.blockcerts.org/">Blockcerts</a>)
- Contract signature (<a href="https://www.docusign.com/">Docusign</a>)
- Internet structure (<a href="https://ipfs.io/">IPFS</a>)
- Bananas? (<a href="https://www.bananacoin.io/">Bananacoin</a> using Etherium)
</div>

- Currently 1,246 currencies across 6,344 markets (<a href="coinmarketcap.com">coinmarketcap.com</a>)

# It's great that it's everywhere, but what is it actually?

## Let's look at some data

<div style="font-size: 20px">
```{js, eval=FALSE}
 {
      "hash": "1dae2ffb42469c6afad79fc0a7454ea704d444497151971bf36aca31e3a1a7c4",
      "ver": 1,
      "vin_sz": 1,
      "vout_sz": 2,
      "lock_time": 0,
      "size": 225,
      "in": [
        {
          "prev_out": {
            "hash": "976656f4e6008b29b4fad81b94347da2a3c8c49e10eee3c9bf27a0ad86c8de38",
            "n": 1
          },
          "scriptSig": "304402204a5eefcce2c9d87743eb099fec6c76731164cf4be9d30c56e60b7cdf9d0c374902206fde8d03cca5cccb67c9a8f2e0144297cbf9361dd63222de78e28d2f7b89369501 0305594a7ecc821f6e9392f0ef757eaee8430b83cedf76eb359b6c247e5299b3ce"
        }
      ],
      "out": [
        {
          "value": "10.00000000",
          "scriptPubKey": "OP_DUP OP_HASH160 fef3cbaa76b111e4fb6a97ee3e5931ced799f201 OP_EQUALVERIFY OP_CHECKSIG",
          "address": "1QF4gwQi3bfU8gMEFnudYroHcdnzizXgFz",
          "next_in": {
            "hash": "cd6e7702c8271e9337ecc18ecb7393b2b38e7e5830b99c6bc3456e2684698e4f",
            "n": 0
          }
        },
        {
          "value": "18.68775000",
          "scriptPubKey": "OP_DUP OP_HASH160 ecf7a3fbf1b866e12f147ff792242331ec575bec OP_EQUALVERIFY OP_CHECKSIG",
          "address": "1Nby8e7oL1yEWYYwXZAmjSSodB4161rwzH",
          "next_in": {
            "hash": "36a032c515f88450a858a5b4efe57f119fb43bb1bc5db6e5e87f72cc5e9bf724",
            "n": 0
          }
        }
      ],
      "nid": "06406fb7ffbadd5fcf2e42e3fa43ec9de8a2bb271a799bc21c9a12f5e27916cc"
    },
```
</div>

- 64GB of this stored in binary files as of 2017 Oct 28. 

## Block 1
<span style="font-size: 20px">
ID: 000000000000000000f061205567dc79c4e718209a568879d66132e016968ac6 -- Time: 2016-12-17 20:26:21 UTC
</span>

<iframe src="http://rmc.link/Bitcoin_block3.html" height="700px" width="100%"></iframe>

## Block 2
<span style="font-size: 20px">
ID: 000000000000000001806a922d4d35a37ad9324c690f72d556c6445cb7a9c214 -- Time: 2016-12-17 20:26:24 UTC
</span>

<iframe src="http://rmc.link/Bitcoin_block2.html" height="700px" width="100%"></iframe>

## Block 3
<span style="font-size: 20px">
ID: 0000000000000000000cdc0d2a9b33c2d4b34b4d4fa8920f074338d0dc1164dc -- Time: 2016-12-17 20:29:03 UTC
</span>

<iframe src="http://rmc.link/Bitcoin_block1.html" height="700px" width="100%"></iframe>

## Prior 3 Blocks (30 minutes)

<iframe src="http://rmc.link/Bitcoin_blocks_30min.html" height="700px" width="100%"></iframe>

## Why is this popular with illegal activities?

<div class="code-blend">
```eval=FALSE
        Electronic  Anonymous  Payment_Guaranteed  Not_Traceable
Ideal       ✓          ✓              ✓               ✓  
```
<div class="fragment">
```eval=FALSE
Cash
```
</div>
<div class="fragment">
```eval=FALSE
            ✘          ~               ~               ✘
```
</div>
<div class="fragment">
```eval=FALSE
Credit
```
</div>
<div class="fragment">
```eval=FALSE
            ✓          ✘              ✘               ✘
```
</div>
<div class="fragment">
```eval=FALSE
Crypto
```
</div>
<div class="fragment">
```eval=FALSE
            ✓        ✓/~              ✓              ✓/~
 > Bitcoin  ✓          ~               ✓               ~
```
</div>
</div>

## Supply and demand

- Dash: `r cryptoMC('dash')`
- Monero: `r cryptoMC('monero')`
- Zcash: `r cryptoMC('zcash')`
- Verge (VGX): `r cryptoMC('verge')`
- PIVX: `r cryptoMC('pivx')`
- Zencash, zcoin, DeepOnion, ...
 
> For comparison, BTC: `r cryptoMC('bitcoin')`

# Why should we, as accounting researchers, care?

## Accounting systems

1) Control systems
    - Project Gutenberg uses it to validate their files <a href="https://explorer.factom.org/chain/00511c298668bc5032a64b76f8ede6f119add1a64482c8602966152c0b936c77">IDs here</a>
        - <a href="https://www.reddit.com/r/factom/comments/4igkcw/how_can_i_actually_download_the_project_gutenberg/d2zj9ew/">Comments from Chief Scientist at Factom</a>
2) Inventory systems
    - <a href="https://www-03.ibm.com/press/us/en/pressrelease/51712.wss">IBM Fabric (Hyperledger)</a>
3) Distributed **ledger**: <a href="https://www.factom.com/">Factom</a>
    - Property rights in Hondurus @ <a href="https://www.economist.com/news/briefing/21677228-technology-behind-bitcoin-lets-people-who-do-not-know-or-trust-each-other-build-dependable">Economist</a>

## Can it replace accounting?

> Blockchain allows someone to claim ownership over an asset in a trustworthy manner visable to all

> - It does not allow them to claim disownership
> - It only implies a lower bound of ownership
>     - Conservative for assets
>     - Not so conservative for liabilities...


## What/who to watch

- Etherium and hyperledger
    - Platforms for blockchain
- Microsoft, IBM
    - Large R&D efforts
- ICOs
    - <a href="https://www.kickico.com/campaigns/999/ico">Example campaign</a>
    - <a href="https://web.archive.org/web/20170907213800/https://www.kickico.com/campaigns/999/ico">During campaign</a>
    - <a href="https://etherchain.org/account/0x714f986ca3a990d674b4c20a7789334931ce8455#txreceived">Some transactions</a>

## Thanks

```{r ending, echo=FALSE, warning = FALSE, message = FALSE}
library(visNetwork)
nodes <- list(id=list.files('Icons-hyperledger'))
nodes$group <- "hyperledger"
nodes$id <- c(nodes$id,list.files('Icons-ethereum'))
nodes$group[nodes$group != 'hyperledger'] = 'ethereum'
edges = list("to"=c(), "from"=c())
nodes <- as.data.frame(nodes,stringsAsFactors=FALSE)
edges <- as.data.frame(edges,stringsAsFactors=FALSE)
nodes$image.unselected <- paste('Icons-',nodes$group,'/',nodes$id,sep='')
nodes$shape <- "image"
visNetwork(nodes, edges, width="100%", height="600px")
```

