Ported from https://github.com/zcash/zcash/commit/6a7cfdea54a9469ac1234e32db9d2fed0bb146af which did not apply cleanly.