Prayer Blockchain – background thoughts 2

I am working on my talk on the prayer blockchain. And I wrote down a bunch of my thoughts on exchange and prayer that
are not appropriate for the talk but I figured I would post it.

The prayer blockchain is about rethinking exchange and value through the metaphor of prayer.

That is a long title and blockchain is sexy so you you know prayer blockchain

So lets unpack what I mean by a prayer blockchain and why I built it and what you can do with it

If you want more information please go to the first part of this post. I am going to talk about tech now.

So we have technologies for mediating these types of exchanges. We have money for mediating debt, we have parties and things for mediating gifts, and we have religion for mediating prayers.  These are structures that enable us to create these types of exchanges and activities. They are a type of technology.

With the blockchain we have a true revolution in mediating debt.  This is for three reasons that I have not created good names for but lets call it a) trustless, b) history c) programmability.

So first off trustless. Who decides what has value? This is what trust means.  Why does the dollar have value – “In God We Trust”.   This is not a quantitative value, like how do we know a dollar is a dollar, but an existential value. How do we know that something is worthy of value?  How do we know this is a dollar and not monopoly money. Which system of exchange can I use this within?

The real utility of blockchain technology is that we can create a digital asset and know exactly (or limit) how many times it is exchanged or reproduced.  This is a difficult issue because the defining characteristic of digital technology is that it is infinitely reproducible.  A piece of software unlike a sheave of wheat or a bayblade has zero marginal cost and can be replicated with out any additional work.  But something that can be infinitely generated can be a bad record or store of value if it is easy to create fictional entries.

With CONSENSUS we replace the the standard of value, which has been an authority institution such as the government or religious authority, with a concept or algorithm CONSENSUS.  Now this can be an authority consensus, such as proof of authority used by many private blockchains, or it can be something else such as proof of stake or proof of work.

So who decides if a payment has been sent, or a gift has been exchanged, or a prayer has been made?

Does this matter for a prayer? We can kinda see why this would be important for a payment or a gift.  It is a material exchange. A prayer is an immaterial exchange why do we care if there is a record of it?  I am not sure. but I am curious what happens if we make all these invisible or immaterial desires manifest. What if we refine our prayers/intentions/affirmations? What will this do to our culture.  We are in a time where all things that were once firmly material are in part immaterial, controlled by data and evolving algorithms rather than by physical mechanical processes. Perhaps the immaterial and invisible and half understood desires embodied by prayers would benefit from a material intervention. Perhaps a record of prayer would illuminate our prayers and help concretize them in some way.  Since prayers are personal, it makes sense that we want to use an algorithm to determine what prayers have been made and who has made them.

What is at stake in a double spent prayer. I am not sure,   It is perhaps, an idea of False Consciousness :

False consciousness” is a concept derived from Marxist theory of social class. The concept refers to the systematic misrepresentation of dominant social relations in the consciousness of subordinate classes

from the internet –  D. Little.

Lets say that prayers/affirmations/intentions are a representation of consciousness. To manipulate or falsify this consciousness is to some how damage society at large. To reveal a truthful map of desire is to elevate society.

Ok Lets talk about history.

The blockchain is money with a history. This is both exciting and terrifying. Do I really want to know where that dollar was before the store clerk gives it to me in exchange for a bunch of bananas? But maybe I do. With the blockchain the money itself is just a list of all the transactions ever made. With a prayer token. The prayers are a list of all prayers ever made. These things are cumulative. How do intentions and desires change, how are they refined. How can I build or augment the prayers of someone else? How do we share the same thing.

In our society there is a premium on uniqueness, on scarcity, and on innovation.  With prayer we can reverse that, how do we all have similar prayers, the prayers that are the strongest are the ones that we share, and what prayers persist through time that express some deep ineffable sense of what it is to be a human being or cyborg (versus perhaps a robot or AI).

Now lets talk about programmability.

So this is nothing new, prayers have for ever been intertwined with algorithmic operations to achieve certain actions. We call this ritual. It is hard to look at something like the iching or geomancy  and not see an algorithmic computational process.  However, historically money has been divorced from action. In order for your money to do anything you need the help of the law (or business). In our society legal contracts enforce complicated economic transactions.  With computational money (blockchain or otherwise), we can can create the contract as a piece of code attached to the money itself.    From the point of view of prayer this is fascinating.  What is the relationship between counting the rosary beads and saying our lords prayer, what is the relationship between burning money and praying to my ancestors, what is the relationship making a prayer and making a donation.  What if our prayers executed the ritual itself?

Again,I am not sure if this is important. There is something about the physical act of embodying a ritual that makes it powerful. If we offload that to a computer what happens then? But there is also something powerful about conceptualizing a ritual in algorithmic terms and rethinking non-linear rituals, rituals of O(n log n) complexity. NP-hard rituals. Why do we have ritual activity in the first place? Is this just some sort of dysfunctional neurotic action that prevents us from doing something useful in the world. In which case YES – lets totally offload it to a computer.  Does it satisfy some deep human desire to connect with something eternal, ephemerial, illogical, and/or unknown or unknowable?  Perhaps yes too, but why not conceptualize it in the way that we have created conceptual art – what is conceptual prayer?

Is the blockchain the only technological enhancement we could have for prayer? No. We could have local, rumor based prayer on the scuttlebutt network.  How is this sort of prayer different from a blockchain prayer.  Popular prayers are popular because they are propagated by the network. In the a blockchain or token based prayer system prayers are cloned tokens.  In a rumor based prayer system you are more interested in the prayers closer to you in your network, in a blockchain system, prayers are equally accessible.  The blockchain is about exchange of value. By putting your prayer on the blockchain you are entering into an explicit exchange. Rumor networks are about communication. By sending or following a prayer you are not exchanging energy but amplifying.  You are part of the prayer tech, you are not the one doing the praying.

What about a prayer consensus algorithm?  When I first started this project I was thinking that we needed something like proof of prayer instead of proof of work. That I needed a new form of consensus.  That prayers would only be executed (or prayed) depending on the number of nodes running the prayer blockchain -like prayer wheels.  But I have been able to incorporate this into the prayer token smart contract. It may be more elegant to build a separate blockchain for prayer. I look at established religious institutions like the Catholic church and it is as if they have a separate blockchain with a distinct consensus algorithm running besides that which governs secular institutions. But then the Catholic church is just the structure of the Roman empire in new clothes, so these institutions themselves bootstrapped on top of existing structures.

https://renaudfabbri.com/axial-age/

Prayer Blockchain – background thoughts 1

I am working on my talk on the prayer blockchain. And I wrote down a bunch of my thoughts on exchange and prayer that
are not appropriate for the talk but I figured I would post it. This is the first part…

The prayer blockchain is about rethinking exchange and value through the metaphor of prayer.

That is a long title and blockchain is sexy so you you know prayer blockchain

So lets unpack what I mean by a prayer blockchain and why I built it and what you can do it

(I am going to include this in all my prayer blockchain quotes)

First lets talk about Exchange
There are many different ways to exchange things and many different reasons.
The most popular way to exchange something is through the medium of money. I give you $2 and you give me a coffee, probably like $3.50.
I really never thought about money except perhaps how to get it, or worrying how to save it or grow it.
But I really never thought about money from first principles. What IS it? where did it COME from? It is so pervasive
it is almost like the air we breath – the medium that we move through

Years ago, I read David Graeber’s book DEBT – and it blew my mind. I was like oh Money is a social construct.
I am a thoughtful and inquisitive person and I am not sure why it took me so long to see this but there you have it.
Many people trace records of transactions back to temple donations. Like how many sheaves of wheat someone donated or took. Money replaced this in what is called the AXIAL age (by Karl Jaspers). This is the time when the great philosophical systems of the world began. We have Presocratic greek philosophy, Confucianism, the Buddha, the Upanishads, the Hebrew bible. It was the creation of symbolic systems of value and exchange (economic and spiritual). When you have symbolic objects the question arises of how we affix and transform the values that those symbolic objects contain.  This can be something like sin, or a computer variable.

These are all systems of reasoning and value, and Money too is a symbolic system of reasoning and value.
Money is just bits of paper that people exchange to keep track of what people own one another. In this respect it is related to DEBT.
DEBT is the idea that you always owe someone something and it too is a pervasive feeling and metaphor in our culture. The thing about money is that it is quantifiable. You always know exactly your relationship to someone else through this particular perspective.

But this is not the only way to exchange things The other big method of exchange is the Gift. The gift is another way to exchange goods and the gift giver and gift receiver are forever linked in a non-quantifiable relationship to one another. Money is fungible, that means each dollar is the same as ever other dollar. It is easy to repay someone that has loaned you a dollar. Gifts are generally non-fungible. A fidget spinner and a bayblade are not the same thing. If I give you a gift of a bayblade it is not equal to the gift of a fidget spinner. Granted I could give someone a gift of $10 or bitcoin. And then the gift would have a specific quantifiable value. But when people exchange gifts there is generally not expectation of payback although there is a feeling of indebted. It is curious who benefits more from the gift – the gift giver or the gift receiver. And then there are material benefits beyond the gift itself. If I am a philanthropist, donating buildings, then my gifts grand me social status and perhaps bring me into a network or reciprocal gift giving.

This is codified more strongly in some cultures. In china for example there is the notion of Guanxi, which is a network of gift giving bringing two people into relation through the exchange of gifts which can never fully be reciprocated.

But back to exchange. What is exchange really about? It is about desire and connection. If I exchange something with someone else it is because someone WANTS something, a new car, or a house, status, or power. Even in the case of gift giving the gifts are not given with out some purpose, if it just the desire to give aa gift in order to give pleasure to another person.
Exchange also serves to solidify connections. Gifts more so than money. If we think about exchange as an equation and the equal sign as a connection. We can easily make both sides of the equation equal in the case of monetary exchange and some how weaken the importance of the equal sign or evaluator. But in the case of a gift we can never make both sides equal since gifts are unquantifiable.

What about PRAYERS! Yes that is my project. What is a prayer. A prayer is a sort of unmet desire or a desire for a gift. It is a connection with something immaterial. If we think about exchange as an equation and money as an equation where both terms can equal one another, and gifts where both terms never equal one another, them a prayer is where there is only one term. It is like a partial differential equation. There is something beautiful and powerful to me about this. That prayers represent an exchange or connection with not only something unquantifiable but immaterial.

In Parmenides’ poem “On Nature” – our protagonist, the goddess, talks about what we can talk about. We can only talk about what IS we can not talk about what IS NOT. There are three interpretations. That this is existential or ontological. We can only talk about what exists, we cannot talk about what does not exist. Another is that it is veridical. We can only talk about what is TRUE, not what is not TRUE. The third is predicative (I think) or essentialist, we can only talk about what something is. Like I am a brunette. We cannot talk about what something is not, like I am a blond (when I am a brunette). Why this is the case and which sense represents the statement of the goddess? This is beyond a blog post about the prayer blockchain.

I always thought this had something to do with the ancient greek mood of the optative which is for talking about things that do not exist. If it rained today I would have worn a raincoat but it did not rain so i did not wear a raincoat. We can say this, so I don’t think this is what the goddess is referring to.

The IS in these statements function as the equals sign in an equation that reconciles values. The veridical function is the function of money. Something is true when both sides of the equation equal one another. The predicative function is the function of the gift, when something is non commensurate with anything else or unquantifiable. It is what it is- it is definitional. The existential function is the function of prayer, the fact that I have a desire or wish is all I need for it to exist. It has no other term that it relates to. I have no idea where I am going with this, but I think a lot about Parmenides, it is the name of my computer.
Back to Prayers.
This is sort of an unmet desire or an unreciprocated desire. It is like the desire for a gift. Now there are many different kinds of prayers in different cultures. This can be a prayer like “Now I lay me down to sleep I pray the lord my soul to keep..” Or the Jewish declaration of faith – the Schma – Hear O Isreal the lord is god the lord is one. Is this a prayer or an affirmation? I am not sure, but the line between prayer and affirmation is blurry. Or a Hindu prayer that you may say as a religious person or a bourgeois yoga practitioner. Ohm na mo guru dev na mo – “I bow to the infinite teacher within.”

So I am interested in how we can reformulate our conceptions of value and exchange to include these sorts of desires.

Beyond_the_valley_of_the_dolls_Poster

Strawberry (er Ethereum) Alarm Clock

In the epic film, Beyond the Valley of the Dolls, by Roger Ebert and Russ Meyer. There is a band called Strawberry Alarm Clock that plays in the party scene.  The movie is nutty-  a campy midnight movie written by Roger Ebert?!?!?  It is quite different from the book, The Valley of the Dolls, by Jacqueline Susann, another cultural milestone. But lets proceed to the business at hand – the blockchain.

This morning I worked on scheduling prayer executions on the Ethereum blockchain. Lets say I have a prayer, Miserere Mei Deus (really a song but lets go with prayer it has an interesting backstory too). I want it ‘prayed’ Easter at 6pm, Rome time.  There is no way to do that out of the box on the Ethereum blockchain.

So what are our options? I found 3: AION, Ethereum Alarm Clock or Oraclize. There are a few AION projects. This is the one to look at. It uses an off-chain system to trigger the contract execution at a later date. This is not decentralized, this does not look like a robust solution.

Oraclize lets you access data external to the blockchain (like an oracle).  But this would make the prayer project dependent on something centralized which would defeat one of the reasons I am using the blockchain in the first place.

Enter Ethereum Alarm Clock – another non-decentralized service. This uses another set of nodes -time nodes (i thought time lords at first which is a cooler name) to monitor the schedule.  Also not going to use this.  Reading the documentation has given me a headache, and all for a side chain! Oh the humanity.

This is what I have decided to do:

I am baking into the prayer amplifier and prayer creator a new function – the prayer scheduler or ‘pray’ function.  This is a public function so I plan to ping it from my ‘glowing prayer orb.’  Whenever someone prays, amplifies a prayer, or runs the glowing orb ($99.99), the smart contract checks and sees any prayers have been scheduled in the past but not executed (prayed). And it then ‘prays’ those prayers.

I am ok with this strategy. Indulgences alone will not get you into heaven.  You cant just buy your prayer. If other people are not praying then your prayer will not be executed. As the ancient Romans used to say – Do ut Des.

https://www.researchgate.net/publication/265818296_Music_and_Consciousness

Consciousness and Music – The Spotify API

This image is from a paper that I have not read, but I liked the graphic because music like brain activity is represented as a wave.  Is reality a particle or a wave? continuous or discrete?

My husband used to be a DJ and would describe to me the ways that he would structure a set to excite a crowd or calm a crowd. And most people connect certain songs to their personal histories or memories, even consciousness.  Many people believe that before we had spoken language we had song.

What is the connection between music and the mind? I have no idea – there are a ton of different thoughts on the matter and this line of thinking is anything but original. I was talking to a friend who was interested in exploring the spotify api to generate playlists to elicit certain emotional or mental responses.   This prompted me to take a look at see what exactly was possible with the API.

This also coincided with a conversation I had at RC with some folks on how personal a music player is. Different people want different things. One person wants to normalize the gain – (ie make all the songs the same volume), another person does not care about this, but wants access to all the songs that he skips on Spotify to help build a playlist.  Is this functionality that we have access to?

First off, this is sort of an amazing project: 30s Drum Machine. It is a drum machine made from 30 second Spotify samples. The repo is on github for your perusing pleasure.

So first off we can read public playlists and create playlists. We can search for artists, albums, tracks.  or playlist based on a number of parameters including bpms (so you can imagine automatically or technically aided DJ sets.

You can get a user’s recently played tracks but not recently skipped tracks. However, you do have access to user’s personalization preference which means you can probably create custom DJ sets on a person or population basis, which is kinda interesting. Imagine a VR world where everyone is in a club but hears a different song with the same beat profile or profile that elicits the same response,

There are a bunch of libraries in various languages referenced on Spotify but a quick google also turns up Haskell and Rust libraries that are not referenced on the Spotify site. Not sure what I am going to do with this, I will probably do something in March if nothing else so that I can have an excuse to have a very very mellow party.

https://blockgeeks.com/guides/smart-contracts/

Alternate Smart Contract Framworks – Codius

I got this really nice infographic from blockgeeks. For those of you that are not familiar with smart contracts, it is a contract that automatically executes when the terms of the contract are fulfilled. It is trustless, so you dont need a lawyer or any other third party to verify the transaction because it is run on a decentralized blockchain.

Last week Benjamin, Tenor and I did a whiteboard session around an idea that Tenor has for a blockchain mechanism for communities. I am not going to talk too much about the idea, because hopefully we will build it and the I can write it up along with demo, but it caused us to look at the smart contract landscape.

But why use a blockchain solution in the first place?  For me the first is public infrastructure: The idea that you can deploy a program and not worry about the dev ops reminds me of the ORM (object relational mapping) spearheaded by Django and Rails. It hides away a bunch of complexity (in ORM that would be SQL, stored procedures and the like), and allows people to work on business logic and specific solutions rather than tech infrastructure or boilerplate.

The second reason is transparency.  Blockchain smart contracts allow anyone to not only see the code, but see how it is executed. It is as if you gave everyone access to your internal databases and log files. Sure this is possible without a blockchain solution, but blockchain gives you a standard way to describe and access this information.

With decentralized smart contract networks, we do away with the dev ops part of tech infrastructure. One issue with this  is that money is necessary to deploy and execute smart contracts, which in the case of Ethereum and microtransactions, can be onerous – perhaps more than building your own infrastructure and paying an engineer(s). The second issue is the idea of consensus. How do you know that your contract is executing directly? Are you going to run on a public blockchain or a private blockchain and lose transparency. This final question is not one that we have solved completely, but we have started looking at alternatives to Ethereum in order to execute smart contract affordably.

First up was Codius, built by the folks behind the Ripple, XRP, XSpring, etc.  Ethereum has a parameterized approach to smart contracts, you create a solidity contract and pay to deploy it to ethereum and that is it. The currency and the contract are intertwined. Codius is much more open ended.  You create a smart contract in an language you like, wrap it in docker and deploy it to a codius host.  Anyone can be a codius host, it is sort of like a bitcoin or ethereum mining node for smart contracts.   Payments and then made and received through the Interledger protocol that is run on another node (or service). The currency and smart contract in this case is decoupled. It is an interesting alternative to the type of smart contracts initiated by  bitcoin or counterparty or Ethereum, and the goal is to keep the transaction costs down in deploying and executing a smart contract.

We are exploring a few other smart contract technologies but this look promising.

 

https://linoxide.com/linux-how-to/linux-fun-terminal-crazy-output/

Fun Stuff On The Web

This post is inspired by Austin and Paul who made great presentations about fun things you can do in *nix.  I did not know about any of these because apparently I live under a rock.

First off – cowsay.  You basically type in a sentence and then an ascii cow has a word bubble with your sentence. However, there are a ton of flags that you can use to change the cow and the representation and the sentence. And you an write your own cowsay file to further customize the cow. This being *nix, you can pipe it into another command – such as lolcats and print your cow with a gradient. I got all this info from Austin – thanks Austin.

screenshotThen Paul made a presentation on ponysay  and he made a recuse pony file. I am writing this blog post in a van from Phoenix to Tucson, and my friend next to me just said “there is nothing like a recusive pony!”  Indeed!.

So this prompted me to look at other fun things and nix easter eggs.

One I remembered from a long time ago is:

telnet towel.blinkenlights.nl

This is super old – but if you run it you basically watch an ascii version of starwars.

Figlet – this just gives you big unix ascii fonts- but can be fun to pipe.

Some other fun unix commands  are ascii aquarium  (repo) and ascii weatherspect – displaying fish and weather.

If you type :help 42 in vi you get

Screen Shot 2019-02-15 at 2.56.56 PM

rig creates random fake people, which actually may be helpful for testing

sl – creates a steam engine – my boys will love it

sudo apt-get install sl

Games in emacs: go to  /usr/share/emacs/*/lisp/play and ls. In emacs you can play one of these games with Meta-x so Meta-x life – plays game of life.

Screen Shot 2019-02-15 at 3.14.45 PM

While this was a fun diversion, there were a bunch of ‘funny’ unix commands that were in really bad taste and tone def. It makes me realize how some of computing culture needs to change to become more inclusive and empathetic.

Ports in Elm

I recently finished the basic Elm tutorial that Tenor introduced me to. The last assignment was on ports.   This to me seemed very strange. What is an elm port?  Why do we need it? It reminded me of this this Rust WASM feature request:

Request for library: mpsc channels library built on top of the postMessage API #163

This could allow wasm to talk to js via CSP style message passing, different wasm instances to talk to each other without sharing memory, the wasm instances might even be in different threads by using web workers.

So what are Elm ports? Ports are the way that javascript and Elm talk to each other.  In Elm ports, messages are one way. It is not like http or tcp/ip where there is a handshake. I can send a message from JS to Elm, and vice versa, but I do not confirm that the message was received.

It is a pub/sub pattern, where JS subscribes to a port that is populated in Elm, and then sends messages on a port that is then handled in elm.

I did not expect Elm to work this way, but its not that strange. Maybe I can use some concepts and apply them to RUST WASM.

WASM is Magic

A few weeks ago I stumbled upon wasm when I was

  1. Looking for Rust projects to contribute to
  2. Looking for a way to write smart contract that was not in javascript

I came upon wasm for both of these things. So what is WASM? WASM is web assembly. It is a binary format for web application.   You can write an application in Rust, or C, or any language that compiles into web assembly and then load it into a web page. The benefit is near native performance (and not having to use Javascript).   There are also some security benefits to the way that web assembly memory is allocated – the execution stack is separated from the WASM stack. Here is a whole medium piece  someone wrote on JS and memory if you are interested.

I found it very magical writing something in rust and then publishing it as a node package and calling functions in another js function.

There are two resources I looked at for web assembly. The web assembly book https://rustwasm.github.io/book and https://rustwasm.github.io/book/game-of-life/implementing.html. I recommend the second one because it has a really interesting example of canvas integration with WASM. There is also a podcast on this week in rust about WASM.   AND just because WASM was written for the web, and has ‘web’ in the name does not mean it could not be used for other things. It could be like a better type of virtual machine (think JVM) or something. Some other good links are the awesome rust and wasm page and wasm-bindgen examples.  I also heard about an open frameworks-ish library in WASM from Max D.

It also made me think about the way JS communicates to Non JS. So JS and WASM, or JS and elm (ports). I am not sure why this is interesting, but there is something about this sort of interop that I find worth thinking about it.

I still have some more work to do on my personal Rust WASM project, and am going to work with Marko on a Rust WASM version of his breakout speed analysis comparison. I was going to put a link to the heroku deploy – but because of the rust module this is not trivial. I think I need to write a heroku build pack or publish the package to npm. But here is a screen cap – its in the browser !

This is unrelated to WASM, but J has a great blog post about editing our git history. This is super helpful since I sometimes get lazy on personal projects and commit with unhelpful messages. My main git trick is bfg, when I want to remove something that I should not have committed…. It happens.

Capture the Flag

Today the coffee chat bot paired me with Mauricio.  When we met, he was working on pwnable with Cory.  I have never heard of capture the flag games until I started RC. These are games where you have to exploit some security bug in order to ‘capture the flag’.

It was super cool.   We worked on problem 10.  When you click on problem 10 the only instruction you receive is to ssh into a server.

Once you ssh into the server and run ls, you can see a c file, an executable, the flag, and intended solution. You only have permission to view the c file and execute the executable.  The only thing you can do is enter the right argument to the file.

The idea is that when you solve the problem and run the c program  with the correct arguments, then a bash command or script will display the flag. For example in problem 1, when you solve the puzzle the following code is executed:

system(“/bin/cat flag”);

The problems are about system exploitation, but really they are about operating systems and systems architecture. The way to solve the puzzles is by understanding how the computer works,  by inspecting the address locations of various functions, by understanding the stack and the heap, and by inspecting the machine code that is generated.

Problem 1 was about file systems.  There is clue that I misinterpreted as translating something from hex into ascii.

My misinterpretation lead me to read up on files in linux. I read the man page for read and attempted to understand the file descriptor. How do file descriptors really work?? On Linux fd refers to a process in  /proc/PID/fd/. I attempted to look in this directory but had no access. ps -ef also does not work – I dont have access.    The file descriptor also is an index to a table maintained by the kernel which is in index to another table.  This may be the solution to my problem.  But I sort of thought not, since I probably dont have permissions to any of these tables.

Then I methodically started reading the documentation on all the function calls like atoi. SPOILER ALERT.  I discovered that my initial intuition was correct but a bit off the mark – I wont tell you why but it should be obvious. I quickly was able to exploit the bug and capture the flag! What a rush!

Mauricio suggested picoCTF.  I also found this pretty exhaustive list. I got to say, CTF is a real thrill.

Music and Parsers

Photo note -I actually did see a prepared piano performance at Roulette about a decade ago when it was down in Soho. It was amazing! Now on to business.

Here is my first chess to music via Euterpea composition. Its experimental  lets leave it at that…

The Backstory….

A few Recursors and I  planned to write a chess notation parser (pgn) in Haskell last week.  I have been doing the Haskell exercises from this git repo, and I’ve been reading up on the basics from an online book – like WTF is foldable (its not that complex – just something that is reducible to less elements  like a tree or list). I could do some sort of brut force parser, but I wanted to learn something so I broke out my dragon book and dove in!

At this point it became evident that perhaps this project was less about Haskell and more about compilers. As it turned out I ended up not using Haskell at all,  but used Lex/Yacc  – which has fulfilled a decade(s) old wish.

What would a compiler look like if the language was pgn (chess notation) and we were going to compile it to musical notation to be executed by the Haskell library euterpea?What if we played a chess game as a musical composition?

This has been interesting to me for a long time since the 8×8 matrix of the chess board maps to an octave scale.  It is also interesting to me because you could also say that the rook, knight, bishop, king, queen map to the pentatonic scale.   It is also interesting to me because I am interested in transduction taking energy from one system and using it in another, so the energy in chess as powering a musical composition. It brings up for me all sorts of questions like what is the best mapping for this? Is there a best mapping. What will this sound like?  And so forth.

download (3)

Back to compilers! Generally, we think of a compiler as taking some source code and translating into machine code.   This goes like

  1. preprocessor – generate all code from macros and what not
  2. compile – translate the code to assembly
  3. assembler – translate the assembly to binary
  4. linker – link the libraries and other code

I am only interested in the compile piece  at this point – to turn one language into another (and not assembly in this case, but a protocol readable by Euterpea.  Although it is interesting to think about the other pieces. And in the case of compiler or code optimization we do want to look at the machine code or byte code or linking. (And maybe turn that into music too who knows)

To focus on the compiler -what I am interested in doing is

  1. creating a lexical analysis – that is a list of all the tokens in the language
  2. write  grammar that describes the language
  3. creating a parser – that builds the expression tree of how the tokens work together
  4. generate/emit the euterpea code/protocol

Lets get granular. “Here is the PGN format of the 29th game of the 1992 match played in Yugoslavia between Bobby Fischer and Boris Spassky” I took from wikipedia.

[Event "F/S Return Match"]
[Site "Belgrade, Serbia JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
[Result "1/2-1/2"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 {This opening is called the Ruy Lopez.}
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7
11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
Nf2 42. g4 Bd3 43. Re6 1/2-1/2

First I start with the lexical analysis.  This is what decides what and is what is not a token. I am going to throw out everything above the 1. So the game metadata really. I may want to change this in the future – but that is it.  I am also ignoring everything in {} again more metadata, and I am ignoring all spaces. I will keep tokens as Num. and the number 1-8,  abcdefghNBRKQ and /.

Next I attend to the parser or syntactical analysis. There are a bunch of parsers, and parser methodologies I could implement if I end up doing a Haskell implementation but for now I am using Lex/Yacc – which uses an LF parser.  Lex parses the tokens – it is like a bunch of regular expressions. Yacc defines the grammar and the emitter – which is fun because who does not love Backus-Naur Form??

The Lex/Yacc is not close to fully functional. The following  resources have been helpful. Sadly, I experienced a type error stripped all functionality out in an attempt to debug. Let this be a lesson. Commit early and often!

I should do some smart contract programming so I am just going to leave it half baked on github.  I have been playing around with some possible code generators (emitters) for Euterpea.   We can call this semantic analysis maybe (or maybe not). This is where we generate the musical notation for Euterpea. I had a great time doing this. I recorded the playback via quicktime audio recording because the code for saving Euterpea to wav was onerous. However, I think the background noise does add to the ambience. I just need to bump up the gain.

After this experiment, I learned that I should rethink the pitch mapping.  I would be curious to hear another chess game run through this. Will they all sound the same? If this is the case then my mapping definitely needs reworking!

Dipping my toe into compilers after decade(s) has been fun. I want to continue this discussion. Especially building the compiler in Haskell (not lex/yacc, building a recognizer in the lexical analysis (determining whether or not the input is in the language), parser deep dive, a symbol table deep dive, and of course, my favorite, code generation. But for now I am just happy to use the unix glue commands to generate a parser for pgn.