Monday, June 29, 2020

Alexander Hamilton - A Book Review


I just finished Ron Chernow's exhaustive biography of Alexander Hamilton. Before, I didn't know much about the man. Sure, I knew that he was the first US Secretary of Treasury. He's on the ten dollar bill. And yeah, he had that duel thing with Burr. But that was it. (By the way, who even was Burr?)

Then Lin-Manuel Miranda's musical came out. It made me realize how much about Hamilton that I didn't know, and how intriguing and deep he was as a character. I knew there must be so much more about him than what could be told in a three hour musical.

Usually, biographies tell a story about a person, and follow a linear script -- a chronological narrative of the biographee, starting from their birth and ending with their death, listing their achievements along the way. But Chernow's account of Hamilton was different in that he would take the reader on several tangential side quests. For example, he would write very detailed accounts of George Washington, so much so that you'd wonder if you're reading the wrong biography. Or he would go in depth about the Articles of Confederation or the Constitutional Convention. But the reason is clear -- Hamilton was involved in so many aspects of the US government, that to fully understand Hamilton, you had to understand his contemporaries and all the details of the issues surrounding him at the time. As such, Alexander Hamilton is primarily a biography, but it's just as much a book on American history. Personally, I found this book one of the most important in shaping how I view the world (the others being Guns, Germs, and Steel by Diamond, and Goedel, Escher, Bach by Hofstadter, and Fooled by Randomness by Taleb).

I never realized just how fragile the US government was at its infancy. How uncertain and suspicious the people were of the government. Or the numerous hurdles it had to overcome to be legitimized, and even then, there were constant threats of secession. Hamilton was the main driving force even before the ratification of the Constitution, and fought doggedly to preserve the integrity of the document while serving under Washington. Some might argue he had more power than Washington at the time, and even during Adams's administration he was still working behind the curtains, corresponding directly with his Cabinet.

The man was not without flaws. He started off with a bang, suffered huge blows soon after leaving the Treasury, and never fully recovered. Chernow does not hold anything back on Hamilton's follies, and paints a complete picture -- that of a political genius at times and an inexplicable idiot at others. But in the end, his virtues and accomplishments vastly outweigh his mistakes and faulty judgments, and he should be remembered as one of the most important and influential founding fathers.


Some favorite quotes and passages:

(on the Federalist Papers)
Madison was aided by his convention notes and crib sheets from his preparatory reading. Without these scholarly crutches, he confessed, "the performance must have borne a very different aspect." For Hamilton, it was a period of madcap activity. He was stuck with his law practice and had to squeeze the essays into breaks in his schedule, as if they were a minor sideline. Robert Troup noted of Hamilton's haste in writing The Federalist: "All the numbers written by [Hamilton] were composed under the greatest possible pressure of business, for [he] always had a vast deal of law business to engage his attention." Troup remembered seeing Samuel Loudon "in [Hamilton's] study, waiting to take numbers of The Federalist as they came fresh from" his pen "in order to publish them in the next paper." During one prodigious burst after Madison returned to Virginia, Hamilton churned out twenty-one straight essays in a two-month period. On two occasions, he published five essays in a single week and published six in one spectacular week when writing on taxation.

Hamilton's mind always worked with preternatural speed. His collected papers are so stupefying in length that it is hard to believe that one man created them in fewer than five decades. Words were his chief weapons, and his account books are crammed with purchases for thousands of quills, parchments, penknives, slate pencils, reams of foolscap, and wax. His papers show that, Mozart-like, he could transpose complex thoughts onto paper with few revisions. At other times, he tinkered with the prose but generally did not alter the logical progression of his thought. He wrote with the speed of a beautifully organized mind that digested ideas thoroughly, slotted them into appropriate pigeonholes, then regurgitated them at will. (p. 354)


(on his impact)
No other moment in American history could have allowed such scope for Hamilton's abundant talents. The new government was a tabula rasa on which he could sketch plans with a young man's energy. Washington's administration had to create everything from scratch. Hamilton was that rare revolutionary: a master administrator and as competent a public servant as American politics would ever produce. One historian has written, "Hamilton was an administrative genius" who "assumed an influence in Washington's cabinet which is unmatched in the annals of the American cabinet system." The position demanded both a thinker and a doer, a skilled executive and a political theorist, a system builder who could devise interrelated policies. It also demanded someone who could build an institutional framework consistent with constitutional principles. Virtually every program that Hamilton put together raised fundamental constitutional issues, so that his legal training and work on The Federalist enabled him to craft the efficient machinery of government while expounding its theoretical underpinnings. (p. 409)


(on his work style)
Inside his teeming brain, he found it hard to strike a balance between the grand demands of his career and the small change of everyday life. The endless letters that flowed from his pen are generally abstract and devoid of imagery. He almost never described weather or scenery, the clothing or manners of people he met, the furniture of rooms he inhabited. He scarcely ever alluded to days off, vacations, or leisure moments. In one letter, he told Angelica that his "favorite wish" was to visit Europe one day, but he never left the country and seldom ventured beyond Albany or Philadelphia.

Only rarely did he enliven letters with anecdotes or idle chatter. It was not so much that Hamilton was writing for the ages—though surely he knew his place in the larger scheme of things—as that his grandiose plans left scant space for commonplace thoughts. Soon after Hamilton became treasury secretary, Philip Schuyler told Eliza a comical story about her husband's absentminded behavior in an upstate New York town where he once paused en route to Albany. Hamilton must have been composing a legal brief or speech in his mind, for he kept pacing in front of a store owned by a Mr. Rodgers. As one observer recalled:

Apparently in deep contemplation, and his lips moving as rapidly as if he was in conversation with some person, he entered the store [and] tendered a fifty-dollar bill to be exchanged. Rodgers refused to change it. The gentleman [Hamilton] retired. A person [Hamilton] retired. A person in the store asked Rodgers if the bill was counterfeited. He replied in the negative. Why, then, did you not oblige the gentleman by exchanging it? Because, said Rodgers, the poor gentleman has lost his reason. But, said the other, he appeared perfectly natural. That may be, said Rodgers, he probably has his lucid intervals. But I have seen him walk before my door for half an hour, sometimes stopping, but always talking to himself. And if I had changed the money and he had lost it, I might have received blame. (p. 470)


(Eliza recounting her husband's work)
Eliza Hamilton remembered the sleepless night when her husband gave immortal expression to a durable principle of constitutional law. As an ancient lady garbed in widow's weeds, she told the story to a young man who recorded it this way in his journal:

Old Mrs. Hamilton…active in body, clear in mind…talks familiarly of Washington, Jefferson, and the fathers. I told her how greatly I was interested…on account of her husband's connection with the government. "He made your government," said she. "He made your bank. I sat up all night with him to help him do it. Jefferson thought we ought not to have a bank and President Washington thought so. But my husband said, ‘We must have a Bank.' I sat up all night, copied out his writing, and the next morning, he carried it to President Washington and we had a bank." (p. 499)


If Washington was the father of the country and Madison the father of the Constitution, then Alexander Hamilton was surely the father of the American government. (p. 682)


(Hamilton vs Jefferson)
The intellectual spoilsport among the founding fathers, Hamilton never believed in the perfectibility of human nature and regularly violated what became the first commandment of American politics: thou shalt always be optimistic when addressing the electorate. He shrank from the campaign rhetoric that flattered Americans as the most wonderful, enlightened people on earth and denied that they had anything to learn from European societies. He was incapable of the resolutely uplifting themes that were to become mandatory in American politics. The first great skeptic of American exceptionalism, he refused to believe that the country was exempt from the sober lessons of history.

Where Hamilton looked at the world through a dark filter and had a better sense of human limitations, Jefferson viewed the world through a rose-colored prism and had a better sense of human potentialities. Both Hamilton and Jefferson believed in democracy, but Hamilton tended to be more suspicious of the governed and Jefferson of the governors. A strange blend of dreamy idealist and manipulative politician, Jefferson was a virtuoso of the sunny phrases and hopeful themes that became staples of American politics. He continually paid homage to the wisdom of the masses. Before the 1800 election, Federalist Harrison Gray Otis saw Jefferson's approach as "a very sweet smelling incense which flattery offers to vanity and folly at the shrine of falsehood." John Quincy Adams also explained Jefferson's presidential triumph by saying that he had been "pimping to the popular passions." To Jefferson we owe the self-congratulatory language of Fourth of July oratory, the evangelical conviction that America serves as a beacon to all humanity. Jefferson told John Dickinson, "Our revolution and its consequences will ameliorate the condition of man over a great portion of the globe." At least on paper, Jefferson possessed a more all-embracing view of democracy than Hamilton, who was always frightened by a sense of the fickle and fallible nature of the masses.

Having said that, one must add that the celebration of the 1800 election as the simple triumph of "progressive" Jeffersonians over "reactionary" Hamiltonians greatly overstates the case. The three terms of Federalist rule had been full of dazzling accomplishments that Republicans, with their extreme apprehension of federal power, could never have achieved. Under the tutelage of Washington, Adams, and Hamilton, the Federalists had bequeathed to American history a sound federal government with a central bank, a funded debt, a high credit rating, a tax system, a customs service, a coast guard, a navy, and many other institutions that would guarantee the strength to preserve liberty. They activated critical constitutional doctrines that gave the American charter flexibility, forged the bonds of nationhood, and lent an energetic tone to the executive branch in foreign and domestic policy. Hamilton, in particular, bound the nation through his fiscal programs in a way that no Republican could have matched. He helped to establish the rule of law and the culture of capitalism at a time when a revolutionary utopianism and a flirtation with the French Revolution still prevailed among too many Jeffersonians. With their reverence for states' rights, abhorrence of central authority, and cramped interpretation of the Constitution, Republicans would have found it difficult, if not impossible, to achieve these historic feats. (p. 886)

(more on Hamilton's work style)
The Post immediately became Hamilton's newspaper of choice for assailing Jefferson, and all eighteen installments of "The Examination" appeared there under the name Lucius Crassus. Hamilton was no hands-off investor, and Coleman candidly described his pervasive influence on the paper: "Whenever anything occurs on which I feel the want of information, I state matters to him, sometimes in a note. He appoints a time when I may see him, usually a late hour in the evening. He always keeps himself minutely informed on all political matters. As soon as I see him, he begins in a deliberate manner to dictate and I to note down in shorthand. When he stops, my article is completed." Coleman's vignette confirms that Hamilton had a lawyer's ability to organize long speeches in his head and often dictated his essays. Otherwise, the sheer abundance of his writing is hard to comprehend. (p. 916)

Tuesday, January 21, 2020

hash canary

Introduction

One of the most frustrating thing about mining The Bitcoins is when your rig goes down, and you're not aware of it. I would like to know that my mining rig is running at all times without too much hassle. I've taken an existing open source module and jazzed it up a bit to create what I like to call, Hash Canary (shoutout to illo jones for the name suggestion).


Features

  • Real time LED status of a mining rig
  • Notification on your smart phone if the rig goes down
  • Automatic restart of the rig if it is down for more than a specified timeout
  • Daily logs of power usage (needs more work)

Overview

The power drawn by the mining rig is monitored by a smart plug. The smart plug is polled by a Raspberry Pi, once every second. If the power drawn by the rig goes below a threshold, a notification will be sent. If the rig goes down for longer than a specified timeout, the entire rig will be power cycled.

Implementation

You will need:

1. Raspberry Pi Zero W (or equivalent)
2. Unicorn pHAT
3. Soldering iron
4. IFTTT account (ifttt.com)
5. Kasa smart plug HS110 model ( https://www.amazon.com/gp/product/B01DQM4ZC2 )
6. A working mining rig with a motherboard that can automatically start up when power is restored (some motherboards will require a user to hit a switch).


IFTTT steps (optional)

1. Register an account at ifttt.com 
2. From there, create two applets for webooks, one for event named 'rig started' and one for 'rig down'. The strings must match exactly as shown.
3. Optionally create an applet to send you an email when any webhooks are triggered (search for the 'notification' applet)
4. Grab your IFTTT API key and copy it somewhere. Go to https://ifttt.com/maker_webhooks then click on the gear icon at the top right corner of the page.

Raspberry Pi steps

0. It's assumed that the user name is 'pi' 
1. Solder the Unicorn pHat onto your Raspberry Pi Zero W. You need good soldering here; I've had mine go flaky because of poor soldering.
2. Download Raspbian Buster (Sept 2019).
3. Use Balena Etcher (if on Windows) to load the image to an SD card.
6. Insert the SD card in the Pi and boot 'er up!
7. You should be able to find the IP address of the Pi by going to your router and checking for any new devices.
8. SSH into the pi. Once in, type 

sudo raspi-config

to change the password, and set the locale.
9. Download my forked copy of the Kasa smart plug module

cd ~
git clone https://github.com/boltar/hashcanary

10. Install the required npm modules

cd hashcanary
npm install

11. Install the required python modules for unicorn hat

sudo pip install rpi_ws281x
sudo pip install unicornhat

11a. For the time being, you have to manually update a file in the rpi_ws281x python package to fix a bug. I've submitted a fix for it but it seems like it hasn't made into the distribution chain yet. Edit the file /usr/local/lib/python2.7/dist-packages/rpi_ws281x/rpi_ws281x.py

ws.ws2811_fini(self.leds)

before the call to

ws.delete_ws2811_t(self._leds)

Final function should look like this:

    def _cleanup(self):
        # Clean up memory used by the library when not needed anymore.
        if self._leds is not None:
            ws.ws2811_fini(self.leds)
            ws.delete_ws2811_t(self._leds)
            self._leds = None
            self._channel = None

12. Create a unix pipe. This will allow you to see the real time power drawn by your rig.

mkfifo ~/poll_pipe

13. Make poll_rig.sh executable. poll_rig.sh is a bash script to launch the poll monitor.

chmod +x poll_rig.sh

14. Edit ~/hashcanary/examples/simple/downstairs.js to meet your needs. Key fields to update:

var smartPlugPowerMonitor = new SmartPlugPowerMonitor({
  smartPlugIP: "192.168.1.136", // miner downstairs
  iftttMakerChannelKey: "",
  pollIntervalSeconds: 1,
  startTimeWindowSeconds: 3,
  endTimeWindowSeconds: 60*15, // 15 minutes
  startEventName: "rig started",
  endEventName: "rig down",
  pollingCallback: pollingData,
  wattsThreshold: 800,
  cooldownPeriodSeconds: 60,
  eventCallback: eventData
});

- smartPlugIP - This is the IP of your Kasa smart plug. Find it somehow.
- iftttMakerChannelKey - this is the key from IFTTT Step 4
- pollIntervalSeconds: how often to poll
- endTimeWindowSeconds - this is the time to wait before the entire mining rig power cycles.
- wattsThreshold - this is the power threshold in Watts that determines whether your rig is down or up. This requires you knowing what your rig draws during idle and at full mining. example: If your rig typically draws 900-1000 Watts during normal mining, I would set it to 800 (default).


15. Edit /etc/rc.local and add this line at the end (before `exit 0`)

sudo /home/pi/hashcanary/poll_rig.sh

16. Edit ~/hashcanary/equalizer.py to set the Wattage ranges for your rig. The variable is misnamed as voltage, please ignore that. The units are in Watts. 

max_voltage = 990
min_voltage = 950

This will set the scaling for the heartbeat led array.

17. Optionally, if you want to change the color, you can edit the same file, around line 51, to default to a different color other than red. Valid colors are "red", "green", "blue", "yellow", "cyan", "purple", "white".

Operation

1. Reboot the Pi and it should automatically start polling.

2. To see current power drawn by the rig:

cat ~/poll_pipe

3. To restart the polling process

sudo pkill node
sudo ~/hashcanary/poll_rig.sh

4. There is rudimentary logging available at ~/hashcanary/examples/simple/power_usage.txt. At the start of the logging script and at around midnight of each day, it will log the current power drawn. 

Troubleshooting

In some cases, the LEDs may get stuck. This is due to the python script not quitting fast enough before the next polling cycle. Simply kill the python process

sudo pkill python

And it should pick right back up again.


To do

  • Be able to change the color more easily
  • More detailed logging of power usage