HolaMundo con ethereum

Publicado:
Tags:  ethereum jaquerespeis smart contracts

Lista de herramientas

  • testRPC
  • nvm
  • web3
  • geth
  • solc
  • web3

Instalación

Linux

Los siguientes pasos muestras como instalar las herramientas necesarias en Ubuntu 17.04

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
nvm ls-remote
nvm install <la ultima LTS>
npm install -g ethereumjs-testrpc
npm install solc
npm install web3

Mac

Para instalar nvm es necesario tener brew

brew install nvm
nvm ls-remote
nvm install <la ultima LTS>
npm install -g ethereumjs-testrpc
npm install solc
npm install web3

Desarrollo

Con el editor preferido, escribir el contrato, para esto se va a utilizar el lenguage solidity, sin embargo existen otras opciones como serpent.

Para compilar el contrato vamos a utilizar el comando solc --bin --optimize <archivo.sol>

Escribit el siguiente contrato en un archivo llamado Voting.sol

pragma solidity ^0.4.11;
// We have to specify what version of compiler this code will compile with

contract Voting {
  /* mapping field below is equivalent to an associative array or hash.
  The key of the mapping is candidate name stored as type bytes32 and value is
  an unsigned integer to store the vote count
  */

  mapping (bytes32 => uint8) public votesReceived;

  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).
  We will use an array of bytes32 instead to store the list of candidates
  */

  bytes32[] public candidateList;

  /* This is the constructor which will be called once when you
  deploy the contract to the blockchain. When we deploy the contract,
  we will pass an array of candidates who will be contesting in the election
  */
  function Voting(bytes32[] candidateNames) {
    candidateList = candidateNames;
  }

  // This function returns the total votes a candidate has received so far
  function totalVotesFor(bytes32 candidate) returns (uint8) {
    if (validCandidate(candidate) == false) throw;
    return votesReceived[candidate];
  }

  // This function increments the vote count for the specified candidate. This
  // is equivalent to casting a vote
  function voteForCandidate(bytes32 candidate) {
    if (validCandidate(candidate) == false) throw;
    votesReceived[candidate] += 1;
  }

  function validCandidate(bytes32 candidate) returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }
}

Pasos para desplegar el contrato

Ejecutar node

Mientras se ejecutan los comandos, se puede ver su salida y analizarla.

Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

Listar las cuentas existentes en la red

web3.eth.accounts

Compilar el código

code = fs.readFileSync('Voting.sol').toString()
solc = require('solc')
compiledCode = solc.compile(code)
abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)
VotingContract = web3.eth.contract(abiDefinition)
byteCode = compiledCode.contracts[':Voting'].bytecode
deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
deployedContract.address
contractInstance = VotingContract.at(deployedContract.address)
> contractInstance.totalVotesFor.call('Rama')

{ [String: '0'] s: 1, e: 0, c: [ 0 ] }

> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})

'0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53'

> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})

'0x02c054d238038d68b65d55770fabfca592a5cf6590229ab91bbe7cd72da46de9'

> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})

'0x3da069a09577514f2baaa11bc3015a16edf26aad28dffbcd126bde2e71f2b76f'

> contractInstance.totalVotesFor.call('Rama').toLocaleString()

'3'

Opcodes de la EVM

0s: Stop and Arithmetic Operations

0x00    STOP        Halts execution
0x01    ADD         Addition operation
0x02    MUL         Multiplication operation
0x03    SUB         Subtraction operation
0x04    DIV         Integer division operation
0x05    SDIV        Signed integer
0x06    MOD         Modulo
0x07    SMOD        Signed modulo
0x08    ADDMOD      Modulo
0x09    MULMOD      Modulo
0x0a    EXP         Exponential operation
0x0b    SIGNEXTEND  Extend length of two's complement signed integer

10s: Comparison & Bitwise Logic Operations

0x10    LT      Lesser-than comparison
0x11    GT      Greater-than comparison
0x12    SLT     Signed less-than comparison
0x13    SGT     Signed greater-than comparison
0x14    EQ      Equality  comparison
0x15    ISZERO  Simple not operator
0x16    AND     Bitwise AND operation
0x17    OR      Bitwise OR operation
0x18    XOR     Bitwise XOR operation
0x19    NOT     Bitwise NOT operation
0x1a    BYTE    Retrieve single byte from word

20s: SHA3

0x20    SHA3    Compute Keccak-256 hash

30s: Environmental Information

0x30    ADDRESS         Get address of currently executing account
0x31    BALANCE         Get balance of the given account
0x32    ORIGIN          Get execution origination address
0x33    CALLER          Get caller address. This is the address of the account that is directly responsible for this execution
0x34    CALLVALUE       Get deposited value by the instruction/transaction responsible for this execution
0x35    CALLDATALOAD    Get input data of current environment
0x36    CALLDATASIZE    Get size of input data in current environment
0x37    CALLDATACOPY    Copy input data in current environment to memory This pertains to the input data passed with the message call instruction or transaction
0x38    CODESIZE        Get size of code running in current environment
0x39    CODECOPY        Copy code running in current environment to memory
0x3a    GASPRICE        Get price of gas in current environment
0x3b    EXTCODESIZE     Get size of an account's code
0x3c    EXTCODECOPY     Copy an account's code to memory

40s: Block Information

0x40    BLOCKHASH   Get the hash of one of the 256 most recent complete blocks
0x41    COINBASE    Get the block's beneficiary address
0x42    TIMESTAMP   Get the block's timestamp
0x43    NUMBER      Get the block's number
0x44    DIFFICULTY  Get the block's difficulty
0x45    GASLIMIT    Get the block's gas limit

50s Stack, Memory, Storage and Flow Operations

0x50    POP         Remove item from stack
0x51    MLOAD       Load word from memory
0x52    MSTORE      Save word to memory
0x53    MSTORE8     Save byte to memory
0x54    SLOAD       Load word from storage
0x55    SSTORE      Save word to storage
0x56    JUMP        Alter the program counter
0x57    JUMPI       Conditionally alter the program counter
0x58    PC          Get the value of the program counter prior to the increment
0x59    MSIZE       Get the size of active memory in bytes
0x5a    GAS         Get the amount of available gas, including the corresponding reduction
0x5b    JUMPDEST    Mark a valid destination for jumps

60s & 70s: Push Operations

0x60    PUSH1   Place 1 byte item on stack
0x61    PUSH2   Place 2-byte item on stack
…
0x7f    PUSH32  Place 32-byte (full word) item on stack

80s: Duplication Operations

0x80    DUP1    Duplicate 1st stack item
0x81    DUP2    Duplicate 2nd stack item
…
0x8f    DUP16   Duplicate 16th stack item

90s: Exchange Operations

0x90    SWAP1   Exchange 1st and 2nd stack items
0x91    SWAP2   Exchange 1st and 3rd stack items
…   …
0x9f    SWAP16  Exchange 1st and 17th stack items

a0s: Logging Operations

0xa0    LOG0    Append log record with no topics
0xa1    LOG1    Append log record with one topic
…   …
0xa4    LOG4    Append log record with four topics

f0s: System operations

0xf0    CREATE          Create a new account with associated code
0xf1    CALL            Message-call into an account
0xf2    CALLCODE        Message-call into this account with alternative account's code
0xf3    RETURN          Halt execution returning output data
0xf4    DELEGATECALL    Message-call into this account with an alternative account's code, but persisting the current values for `sender` and `value`

Halt Execution, Mark for deletion

0xff    SELFDESTRUCT    Halt execution and register account for later deletion

Referencias

  • https://github.com/creationix/nvm
  • https://github.com/ethereumjs/testrpc
  • https://en.wikipedia.org/wiki/Remote_procedure_call
  • http://ethdocs.org/en/latest/network/test-networks.html
  • https://medium.com/@doart3/ethereum-dapps-without-truffle-compile-deploy-use-it-e6daeefcf919
  • https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2
  • https://github.com/ethereum/yellowpaper

Notas

testrpc -n5

Minar ethereum

Publicado:
Tags:  cryptomoneda ethereum jaquerespeis minar

Requerimientos

  • Minador
  • Ubuntu Server 16.04
  • Opcional(tarjeta de video)
  • Python y python-twisted
  • Ethereum
  • cpp-ethereum

NOTA: Se considera Ubuntu Server, en caso de Ubuntu Desktop algunos requerimientos ya vienen instalados en el sistema.

Instalación

  1. Instalar ubuntu 16.04

  2. Instalar python y python-wisted

sudo apt-get install python
sudo apt-get install python-twisted
  1. Un vez que se tiene instalado el sistema operativo, activar el ppa de ethereum
sudo add-apt-repository ppa:ethereum/ethereum
sudo add-apt-repository ppa:ethereum/ethereum-qt
sudo add-apt-repository ppa:ethereum/ethereum-dev
sudo apt-get update
  1. Instalar ethereum
sudo apt-get install ethereum
  1. Instalar cpp-ethereum
sudo apt-get install cpp-ethereum
  1. Clonar el repositorio de eth-proxy.

  2. Crear un wallet con geth o parity.

  3. Instalar los drivers de vídeo, en el caso de usar una tarjeta de vídeo.

  4. Modificar el archivo de configuración de eth-proxy para usar el wallet.

  5. En el directorio eth-proxy, ejecutar eth-proxy.py

sudo python eth-proxy/eth-proxy.py
  1. Ejecutar ethminer apuntando a localhost
ethminer -F http://127.0.0.1:8080/minador -G

NOTA: La opción -G indica a ethminer que utilice GPU para minar, en caso de no contar con GPU utilice --allow-opencl-cpu.

Referencias

https://github.com/paritytech/parity https://github.com/Atrides/eth-proxy https://launchpad.net/~ethereum/+archive/ubuntu/ethereum http://ethdocs.org/en/latest/ethereum-clients/cpp-ethereum/installing-binaries/linux-ubuntu-ppa.html

Jerk chicken natural

Publicado:
Tags:  allspice comida jerk

La idea

Hace unos días estábamos de vacaciones en pavones y Coco(administradora de la casa rentada) nos llevo unas hojas de Allspice, de una se me ocurrió que podíamos hacer Jerk Chicken, resulta que la hoja tiene muy buen sabor pero no se conserva bien, por lo que no se vende comercialmente.

Ingredientes

  • Hojas de allspice
  • Jengibre
  • Salsa de soya
  • Cebolla
  • Ajo
  • Chile panameño o algun otro
  • Azucar
  • Sal
  • Aceite
  • Jugo de limón

Preparación

Las proporciones dependen de la cantidad y que tan fuerte se quiera, no me gusta hacerlo con medida pero voy a escribir unas instrucciones de mas o menos como lo hice.

En una licuadora agregué(cantidades aproximadas):

  1. Allspice, 6 hojas.
  2. Como 2 centimetros cubicos de jengibre.
  3. Una botella de salsa de soya, aprox 100ml.
  4. Unas 2 cebollas medianas.
  5. media cabeza de ajo.
  6. Un chile
  7. Mas o menos, 5 cucharadas de azucar.
  8. Al gusto, creo que fueron 2 cucharaditas de sal.
  9. Aceite aproximadamente 150ml.
  10. El jugo de 4 limones.

Como programar un microcontrolador stm32 con cpp

Publicado:
Tags:  arm cpp jaquerespeis stm32

Que se necesita

  • Microcontrolador STM322
  • GDB o un debugger, editor de texto o IDE
  • Una maquina con Linux

Requerimientos con Gnu/Linux

  • arm-none-eabi-gcc – The GNU Compiler Collection – cross compilador para ARM EABI (directo en el procesador)
  • arm-none-eabi-gdb – The GNU Debugger for the ARM EABI (bare-metal) target
  • arm-none-eabi-binutils – A set of programs to assemble and manipulate binary and object files for the ARM EABI (bare-metal) target
  • openocd – Debugging, in-system programming and boundary-scan testing for embedded target devices
  • vim – Editor de texto

Terminos importantes

CMSIS = Cortex Microcontroller Software Interface Standard info

Referencias

http://regalis.com.pl/en/arm-cortex-stm32-gnulinux/

Lugares de comida que me gustan

Publicado:
Tags:  comida restaurantes

Estos son algunos de los lugares que mas me gusta vistar para comer.

Lista

  • Ruca che: En moravia, exelente restaurante de carnes.
  • Manos en la masa: Increible brunch en barrio escalante, afuera de Casa Batsu.
  • Go-fish: Pinares, especialidad en mariscos pero todo es muy bueno.
  • Rincon picante: 150 este, soda tapia la sabana, la sopa en la que uno cocina el resto de ingredientes.
  • La asociación china: San José, comida china, conocido tambien como la casa china.
  • Maxi's by Ricky:
  • Patty factory: Cuando quiero una sopa de mondongo y no estoy en Limón, este es el lugar.
  • Soda guiligan:
  • Diagonal a la alizan francesa:
  • Soda tala: El talapindo como tiene que ser, es el mejor desayuno que uno puede probar. facebook
  • Chicharronera hermanos Level:

Utilizar Nikola por primera vez

Publicado:
Tags:  blog jaquerespeis markdown nikola python

Instalación

La forma mas simple de instalar Nikola es con pip y virtual, también se podría utilizar uno de los paquetes de la distribución que se este utilizando, en si son usuarios de Linux.

En el directorio del repositorio del sitio

virtualenv --python=python3 .env
source .env/bin/activate
pip3 install --upgrade "Nikola[extras]"

Primeros usos

En este momento se tiene el sistema instalado, ahora hay que crear el contenido del primer sitio de prueba, estando en el directorio que va a mantener el código, se ejecuta el comando nikola init --demo ., luego se debe de construir el sitio con el comando nikola build.

El siguiente paso es ver el sitio, para lo que va a utilizar el comando nikola serve -b, pero es mucho mas fácil utilizar nikola auto -b para reconstrucciones automáticas.

Utilizar markdown

Para utilizar markdown para crear los post se debe usar uno de los múltiples lenguajes de marcado ligero soportado, para eso se debe de editar el archivo config.py en la raíz del sitio en Nikola.

Primero se debe de verificar que este en la estructura COMPILERS

# 'rest' is reStructuredText
# 'markdown' is MarkDown
# 'html' assumes the file is HTML and just copies it
COMPILERS = {
    "rest": ('.rst', '.txt'),
    "markdown": ('.md', '.mdown', '.markdown'),
    "textile": ('.textile',),
    "txt2tags": ('.t2t',),
    "bbcode": ('.bb',),
    #"wiki": ('.wiki',),
    "ipynb": ('.ipynb',),
    "html": ('.html', '.htm'),
    # PHP files are rendered the usual way (i.e. with the full templates).
    # The resulting files have .php extensions, making it possible to run
    # them without reconfiguring your server to recognize them.
    "php": ('.php',),
    # Pandoc detects the input from the source filename
    # but is disabled by default as it would conflict
    # with many of the others.
    # "pandoc": ('.rst', '.md', '.txt'),
}

Luego se debe de agregar a la estructura del tipo de entrada, en el ejemplo de abajo se agregó la linea, ("posts/*.md", "posts", "post.tmpl") a los dos tipos de entras POST y PAGES.

POSTS = (
    ("posts/*.rst", "posts", "post.tmpl"),
    ("posts/*.txt", "posts", "post.tmpl"),
    ("posts/*.md", "posts", "post.tmpl"),
)
PAGES = (
    ("stories/*.rst", "stories", "story.tmpl"),
    ("stories/*.txt", "stories", "story.tmpl"),
    ("stories/*.md", "stories", "story.tmpl"),
)

Utilizar locales para Costa Rica

Este proceso debería funcionar para la mayoría de idiomas.

  1. Generar el locale necesario con `locale-get
  2. Definir cual es el locale que debe de utilizar Nikola por defecto.
# What is the default language?
DEFAULT_LANG = "es"

# What other languages do you have?
# The format is {"translationcode" : "path/to/translation" }
# the path will be used as a prefix for the generated pages location
TRANSLATIONS = {
    DEFAULT_LANG: "es_CR",
    # Example for another language:
    # "es": "./es",
    "es": "./",
    "en": "./en",
}
  1. Definir el locale que se va a utilizar para es, por defecto es es_ES.
LOCALES = {
        "es":"es_CR.utf-8",
        }

El locale a utilizar puede ser probado, importando locale import locale y llamando al locale necesario locale.setlocale(locale.LC_ALL, 'es_CR.utf-8')

Configuración para la printrbot simple

Publicado:
Tags:  3dprint printrbot

Código:

M104 S{TEMP0} ; set temperature
G21 ;metric values
G90 ;absolute positioning
M82 ;set extruder to absolute mode
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
M109 S{TEMP0} ;wait on temperature line
G29 ; Auto bed levelling
G92 E0 ;zero the extruded length
G1 F{TRAVEL_SPEED} ;

Using US netflix with roku and openwrt

Publicado:
Tags: 

First method

The Roku has no possibility to change the DNS to a specific one, so to use US Netflix with the roku the DNS has to be set in the router.

I don’t like all my DNS traffic going to a DNS that I don’t trust so with options of dnsmasq that comes with openwrt I set DNS Forwarding.

Be careful to change x.x.x.x for the ip address of the DNS service you want to use.

example http://www.unblock-us.com ip 208.122.23.23

in the file /etc/config/dhcp add the following lines below config dnsmasq.

    list server '/netflix.com/x.x.x.x'
    list server '/nflximg.net/x.x.x.x'
    list server '/nflximg.com/x.x.x.x'
    list server '/roku.com/x.x.x.x'
    list server '/mgo-images.com/x.x.x.x'
    list server '/netflix.net/x.x.x.x'
    list server '/netflix.net/x.x.x.x'
    list server '/roku.com/x.x.x.x'
    list server '/scorecardresearch.com/x.x.x.x'

it is necessary to add all that list servers.

This method could work for any other hardware but I have only tested it in the roku.

Second method

At first I was using the first method but I had to keep adding forwarder addresses to the dhcp file.

in “network->firewall->custom rules” add the following rules

iptables -t nat -A PREROUTING -i br-lan -s x.x.x.x -p udp –dport 53 -j DNAT –to-destination y.y.y.y:53
#iptables -t nat -A POSTROUTING -j MASQUERADE

where x.x.x.x is the roku or other device you want to use with a specific dns server and y.y.y.y is the address of the specific dns server.

Instalando RepetierHost en Ubuntu 1404

Publicado:
Tags:  3dprint printrbot

Instalar

  1. Para utilizar la printrbot simple estoy utilizando RepetierHost, estos son algunos de los pasos que seguí para poder imprimir.
  2. Descargar RepetierHost de http://www.repetier.com/download/
  3. Descomprimir y mover la carpeta RepetierHost al lugar donde se desea.

Ej: repetierHostLinux_0_95.tgz

tar -xzf repetierHostLinux_0_95.tgz
mv RepetierHost $HOME

o donde se desea dejar, cd RepetierHost y luego ejecutar configureFirst.sh, lo cual les va a instalar las dependencias del sistema.

./configureFirst.sh

Si da errores al descargar ExtUtils-ParseXS-3.18_04.tar.gz o parecido

Working on SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz
Fetching http://www.cpan.org/authors/id/S/SM/SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz ... FAIL
! Download http://www.cpan.org/authors/id/S/SM/SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz failed. Retrying ...
! Download http://www.cpan.org/authors/id/S/SM/SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz failed. Retrying ...
! Download http://www.cpan.org/authors/id/S/SM/SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz failed. Retrying ...
! Failed to download http://www.cpan.org/authors/id/S/SM/SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz
! Failed to fetch distribution ExtUtils-ParseXS-3.18_04
--> Working on ./xs

es necesario actualizar la linea 127 en Slic3r/Build.PL y cambiar

system $cpanm, 'SMUELLER/ExtUtils-ParseXS-3.18_04.tar.gz';

por

system $cpanm, 'SMUELLER/ExtUtils-ParseXS-3.24.tar.gz';

Luego ejecutar de nuevo configureFirst.sh como anteriormente.

van a ver unos errores en las pruebas pero el sistema va a funcionar bien.

Al abrir RepetierHost es necesario como primer paso configurar la impresora, para esto van a "Printer Settings" y utilizan la siguiente configuración

En la pestaña de connection

port: /dev/ttyACM0
Baud Rate: 230400
Trasfer Protocol: Autodetect
Reset on Connect: Disabled
Reset on Emergency: Send emergency command and reconnect
En la pestaña Printer

Defautl Heated Bed Temperature: 0

En la pestaña Printer Shape

X MAx 100
Y Max 100
Print Area Width: 100
Print Area Depth: 100
Print Area Height: 100

Cuando tenga mas recomendaciones las agrego, si alguien tiene alguna recomendación se lo agradecería para agregarla.

Optimización de apache2

Publicado:
Tags:  apache keepalive optimizacion web

Primero hay que revisar cuales módulos están cargados, esto se puede hacer con

apachectl -M

Lo ideal es tener solo los módulos necesarios para que el sitio funcione, la cantidad de módulos influye en e tamaño de cada proceso de apache que se encuentra corriendo.

HostnameLookups off

Cuando un cliente el accede el servidor web, se crea una bitácora en access.log, si esta directiva esta en On se busca el nombre en el servidor de nombres, aun con un cache de dns esto es muy lento.

Cuando se establece una conexión esta se deja escuchando por un tiempo por si se le hace una nueva petición, en el caso de tener muchos visitantes y dejar la conexiones abiertas por mucho tiempo, se crea un problema, por eso se puede bajar el tiempo para poder servir nuevas peticiones. (Esta altamente ligado al MaxClients).

KeepAlive On
KeepAliveTimeout 2

Para el momento de calcular MaxClients.

Una buena referencia es MaxClients = (total de memoria)/(promedio de memoria utilizada por cada proceso de apache)

Una buena manera de ver el tamaño de un proceso de apache es con el comando ps -ylC apache2 --sort:rss

Con esto se puede ver el tamaño del proceso mas grande de ultimo.

Una suma de la columna del rss nos da un valor del total de memoria que esta usando el proceso, esto puede aumentar porque no todos los procesos tiene el mismo tamaño.

ps -ylC apache2 --sort:rss | awk '{SUM += $8 } END {print SUM}'

Hay que tomar en cuenta también el resto de procesos del servidor.

Utilizando top y acomodando por rss podemos ver los procesos que están utilizando mas memoria, entre estos deberíamos encontrar los procesos de apache y el o los de la base de datos si es que se tiene una.